vue

2019-06-05  本文已影响0人  stephenoo

vue基础知识部分

扯淡前言

构造器

缩写

new Vue({
el: "#app",
data: {
firstName:'Ji',
lastName:'RenGu'
},
computed:{
fullName(){
return this.firstName+'----'+this.lastName;
}
}
})

* 计算缓存vs方法(Methods)
    * 计算属性computed具有缓存,而methods无缓存
* Computed属性vs 侦听器(Watch属性)
    * watch方法--观察Vue实例上的数据变动,只要指定的数据改变就会执行预定的函数

                            watch
<div id="app">
    {{msg}} <br> 
    改变了吗? {{isChange}}
    <button @click="change">改变</button>
</div>

new Vue({
  el: "#app",
  data: {
        msg:'欲穷千里目',
      isChange:'No'
  },
    watch:{
    //只要msg改变,这个方法就会执行
    msg(val,oldVal){
        this.isChange = 'Yes'
    }
  },
  methods:{//不得不说ES6写起来真爽
    change(){
        this.msg = '更上一层楼'
    }
  }
})

*   计算setter 和getter
    *   get和set,顾名思义,一个是获得,一个是设置,常规上来讲,计算属性中都是有get和set方法的,默认是只有getter方法,如果需要的话,自然,你也可以写一个setter方法.来个例子,诸位往下看:
        ```

        ```
                      get和set

        ```

        <div id="app">
        此时的onpiece: {{onepiece}} <br>
        此时的msg: {{msg}} <br><br>
        <button @click="setName">设置name</button>
        </div>

new Vue({
el: "#app",
data: {
name:'Kobe',
msg:''
},
methods:{
setName(){
this.onepiece = 'JorDan'
}
},
computed:{
onepiece:{
get(){
return this.name +'Bryant';
},
set(newVal){
//当你给onepiece设置值的时候set就就会调用
this.msg = newVal+'is the greatest basketball player';
}
}
}
})

class与style绑定

绑定HTML class


     绑定class的几种方式

.classC{
color:red;
}
.classD{
font-weight:bold;
}
.classE{
font-size:20px;
}
.classF{
color:blue;
}
.classM{
display:block;
}
.classN{
display:none;
}

<div id="app">
<h2>class属性绑定</h2>
-------------------绑定变量-------------------------
<div :class="{classA:a,classB:b}">
绑定变量
</div>
-------------------绑定对象-------------------------
<div :class="styleObj">
绑定对象
</div>
-------------------绑定数组-------------------------
<div :class="arrClass">
绑定数组
</div>
-------------------绑定三元运算符-------------------------
<div :class="m==true?'classM':'classN'">
绑定变量
</div>
<button @click="toggle">toggle</button>
</div>



    new Vue({
      el: "#app",
      data: {
       a:true,
       b:false,
       styleObj:{
        classC:true,
        classD:true
       },
       m:true,
       arrClass:['classE','classF']
      },
      methods:{
        toggle(){
            this.m=!this.m;
        }
      }
    })

绑定内联样式

条件渲染

v-if(v-else)是真正的渲染

key

因为加上key默认采取的就是就地复用策略,这个例子,如果不懂,可以在群里问我


### 数组更新检测

*   变异方法(会改变原有数组)
    *   push()
    *   pop()
    *   shift()
    *   unshift()
    *   splice()
    *   sort()
    *   reverse()
*   重塑数组
    *   filter()
    *   concat()
    *   slice()
*   注意事项
    利用索引直接设置一个项时,vue不能检测变动,如: vm.items[indexOfItem] = newValue
    那如果设置某一项的该怎么设置呢?

    ```
      * Vue.set(example1.items, indexOfItem, newValue)
      * example1.items.splice(indexOfItem, 1, newValue)

    ```

    ```

    <div id="app">
    <button @click="setZF">设置第二项为张飞</button>
    <button @click="setGY">设置第三项为关羽</button>
    <ul>
    <li v-for="item in list">
    <input type="checkbox" >
    {{item.id}}---{{item.name}}
    </li>
    </ul>
    </div>

var vmm = new Vue({
el: "#app",
data: {
id:"",
name:"",
list:[
{id:1, name:'李斯'},
{id:2, name:'嬴政'},
{id:3, name:'赵高'},
{id:4, name:'韩非'},
{id:5, name:'荀子'},
]
},
methods: {
setZF: function(){
Vue.set(this.list,1,{id:2,name:'张飞'})
},
setGY:function(){
this.list.splice(2,1,{id:3,name:'关羽'})
}
}
})

* 修改数组长度时,vue不能检测变动,如:vm.items.length = newLength
* 只能用example1.items.splice(newLength)

对与显示过滤/排序结果的两种方法


          计算属性应用于过滤

<div id="app">
{{specialNum}}
</div>

new Vue({
el: "#app",
data: {
nums:[1,2,3,4,5,6,7,8,9]
},
computed:{
specialNum(){
return this.nums.filter((item,index)=>{
return item%3==0;
})
}
}
})

<div id="app">
<ul>
在v-for循环中直接嵌入方法
<li v-for="item in fil(numbers)">{{item}}</li>
</ul>
</div>

new Vue({
el: "#app",
data: {
numbers:[1,2,3,4,5,6,7,8,9]
},
methods:{
fil(nums){
return nums.filter((item,index)=>{
return item%3==0;
})
}
}
})

两个简单的事件处理器


先来一个简单小李子,v-on用来绑定事件

1

<div id="app">
<button @click="num+=1">增加1</button>
{{num}}
</div>

* * *

2

<div id="app">
<button @click="sayHello">点击sayHello</button>
</div>
new Vue({
el: "#app",
methods: {
sayHello: function(){
alert('sayHello')
}
}
})
`### 内联处理器方法 * 访问原生DOM事件的例子,如果click事件不传参数,就默认把原生DOM传递进去`
<div id="app"> //没有传参数,就是原生的!!!
<button @click="showBtnname">显示按钮的名字</button> <br><br>
{{msg}}
</div>

new Vue({
el: "#app",
data: {
msg:''
},
methods: {
showBtnname: function(e){
this.msg = e.target.innerText;
}
}
})


----------------------------html---------------------------------
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos">
<label>
<input type="checkbox" v-on:change="toggle(todo)" v-bind:checked="todo.done">

  <del v-if="todo.done">
    {{ todo.text }}
  </del>
  <span v-else>
    {{ todo.text }}
  </span>
</label>

</li>
</ol>


</div>
----------------------------js---------------------------------
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
----------------------------css---------------------------------
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}

li {
margin: 8px 0;
}

h2 {
font-weight: bold;
margin-bottom: 15px;
}

del {
color: rgba(0, 0, 0, 0.3);
}

事件修饰符

按键修饰符


<div id="app">
<button @click.ctrl="num++">num+1</button>
{{num}}
</div>

new Vue({
el: "#app",
data: {
num:0
}
})


vue2.1.0新增 按键修饰符

* 多选列表(绑定一个数组,数组的内容是所有的选中项的value)

    ```
    <div id="app">
    <select v-model="selected" multiple>
      <option>A</option>
      <option>B</option>
      <option>C</option>
    </select>
    <br>
    <span>Selected: {{ selected }}</span>
    </div>

    new Vue({
      el: "#app",
      data: {
        selected: []
      }
    })
    ```

* 动态选项
    ```
    <div id="app">
    <select v-model="selected">
      <option v-for="option in options" v-bind:value="option.value">
        {{ option.text }}
      </option>
    </select>
    <span>Selected: {{ selected }}</span>
    </div>

    new Vue({
      el: "#app",
      data: {
             selected: 'A',
        options: [
          { text: 'One', value: 'A' },
          { text: 'Two', value: 'B' },
          { text: 'Three', value: 'C' }
        ]
      }
    })
    ```

修饰符

算了,这点太简单了,不给例子了,自己写去吧,别来烦我,有不会的群里问......

v-model与组件

组件

使用组件

    Vue.component('my-comp',{
        template:'<h3>我是新出炉的组件</h3>'
    })
    new Vue({
      el: "#app",
      data: {

      }
    })
    ```

        ---------------------------------下边是正确的-----------------------------------
        <div id="app">
         <table>
           <tr>
             <td is="my-comp"></td>
           </tr>
         </table>
        </div>

        new Vue({
          el: "#app",
          components:{
              'my-comp':{
                    template:'<td>我是组件td</td>'
            }
          },
          data: {

          }
        })
        ```

* 不受限的情况--使用字符串模板
    * <script type="text/x-template">  怎么用呢?给大家来个例子吧!

      ```
      -------------------------------HTML-----------------------------------------
      <div id="app">
       <table>
         <tr>
         <template>
             <my-comp></my-comp>
         </template>
         </tr>
       </table>
      </div>

      <script type="text/x-template" id="myComponent">
                  <td>This is a component!</td>
      </script>

      -----------------------------------JS----------------------------------
      new Vue({
        el: "#app",
        components:{
            'my-comp':{
                  template:'#myComponent'
          }
        },
        data: {

        }
      })
      ```

    * JavaScript内联模板字符串(第二种也给大家解释一下是什么意思,什么是字符串模板)

      ```
      <div id="app">
       <table>
         <tr>
         <template>  //这个就是字符串模板
             <my-comp></my-comp>
         </template>
         </tr>
       </table>
      </div>
      ```

    * .vue组件  (第三种不解释了,用了那么多遍了,要是还不会,我就开始疯狂嘲笑你)

* data必须是函数,在组件中使用data中定义的数据,必须使用函数返回,其实这事要说为啥,还得从根上说,我自己的理解,最根本的三个字就是作用域,目的就是为了防止组件中使用的data和vue实例中的data进行相互污染,有机会的话可以给大家讲一下,但是这不是三句两句就能讲清楚的,门票一人5毛怎么样?

    ```
    <div id="app">
    <mycomp></mycomp>
    </div>

    new Vue({
      el: "#app",
      components:{
          'mycomp':{
                template:'<button>{{btncount}}</button>',
           data(){
              return {btncount:8}
            }
        }
      },
      data:{
          btncount:10
      }
    })
    ```

Prop(子组件从父组件获得数据)

自定义事件(子组件将数据传回父组件)

* 例子

    * html及实例部分和注册组件部分

      ```
      <div id="app">
        <price-input :value="price" @input="isinputing"></price-input>
        {{price}}
      </div>

      new Vue({
        el: "#app",
        components:{
            'price-input':{
              template:"<input type='text' @input='update($event.target.value)' />",
            props:['value'],
            methods:{
                update(val){
                  this.$emit('input',val)
              }
            }
          }
        },
        data: {
          price:''
        },
        methods: {
            isinputing: function(val){//此处的value就是子组件传递过来的
              this.price = val;
          }
        }
      })
      ```

非父子组件通信

* 复杂的场景---专门的状态管理模式vuex

使用Slot分发内容

        * 那么单个slot怎么用呢?

            ```
            <div id="app"> 
            <children> 
            <span>12345</span> 
            <!--上面这行不会显示--> 
            </children> 
            </div> 

            var vm = new Vue({ 
            el: '#app', 
            components: { 
            children: { //这个无返回值,不会继续派发 
                template: "<button><slot></slot>(我是button)</button>"
            } 
            } 
            }); 
            ```

* 当父组件中有内容时
    * 子组件中的slot会被父组件中内容所替换。(slot标签也会被替换掉)
* 当父组件中无内容时
    * 子组件中slot内容会被显示出来

        Vue.component('child',{
                props:["items"],
                template:'<ul><slot name="item" v-for="item in items" v-bind:tex="item.text"></slot></ul>'
            });

        new Vue({
            el:'#app',
            data:{
                items:[
                    {text:'老虎'},
                    {text:'棒子'},
                    {text:'鸡'}
                ]
            }
        })
        ```

动态组件

总结

上一篇 下一篇

猜你喜欢

热点阅读