1.data
1.1 当将Vue 实例外声明的属性赋值给data 中的属性,二者变量名相同时,data 中的属性能够简写,如:var items = [1, 2, 3];
赋值data 中的items 时能够这样写:es6
data(){ return{ items, //此处的简写为es6 中的语法 msg:"外界如何获取data 中的数据" } }
1.2 Vue 实例外获取data 属性时有两种方法,
方法一: var msg = vm(Vue 实例名).$data.msg;
方法二: var msg = vm.msg;
而Vue 实例内获取data 内的变量时写法为this.msg,而且data 中的变量不能相互引用。数组
2.methods
2.1 函数没有缓存,每次调用都会从新执行一次,只支持单项绑定,当输入框v-model 绑定函数时,不可修改输入框中的值。
2.2 函数传入当前对象的两种状况,
状况一: 当只要传入元素自己时,缓存
<button v-on:click="say($event)">say hi</button> methods:{ say:function(event){ console.log(e.currentTarget); } }
或者函数
<button v-on:click="say">say hi</button> methods:{ say:function(event){ console.log(e.currentTarget); } }
这取决于函数后面是否带()括号。
状况二: 当须要传入参数或传入参数和元素自己时this
<button v-on:click="say('hi',$event)">say hi</button> methods:{ say:function(message,e){ alert(message); console.log(e.currentTarget); } }
3.computed
3.1 computed 有缓存,只有绑定的变量发生变化时才会调用。
3.2 使用computed 进行双向绑定时get 函数和set 函数用法:双向绑定
sum:{ get:function(){ 绑定数据变化时调用 console.log("计算属性执行"); return (this.englishScore-0) + (this.mathScore-0); }, set:function(newValue){ 计算属性变化时调用 let equalVal = newValue / 2; this.englishScore = equalVal; this.mathScore = equalVal; } }
当get 函数中监听的变量englishScore 或mathScore 变化时get 函数调用。由于缓存的缘由,get 函数第一次调用时console.log("计算属性执行")
会执行,以后get 函数再执行时console.log("计算属性执行")
将不会再执行。
当sum 的值发生改变时set 函数执行,set 函数中传入的参数为sum 改变后的值,能够再set 函数中对相关属性进行操做。code
4.watch
4.1 当watch 中监听对象为对象数组时,正常只会监听数组中对象数量的改变。若是再数组中某个对象的属性发生改变时须要使用deep 深度监听:对象
lists:{ handler: function(newValue, oldValue){ //回调函数 //数组变化时,将数据保存到本地 itemStorage.save(newValue); } , deep:true }
lists 为被监听的对象数组,handler 为监听对象改变时执行的操做,此时deep:true 执行深度监听。
回调函数 handler: function(newValue, oldValue)
中第一个参数为监听对象的变化后值,第二个参数为变化前的值。get
5.directive
5.1 全局指令
全局指令能够在多个Vue 管理的路口下使用,定义指令名时不能加" v- ",而在元素上调用指令时须要加" v- "。回调函数
Vue.directive("指令名", { bind:function(el, binding){ el.style.color = binding.value.输入的对象属性名; } inserted:function(el, binding){ //将传入的内容转为大写 el.innerHTML = binding.value.toUpperCase(); } })
通常对样式style 的操做在bind 中,bind 函数只初始化一次。通常对互动js 的操做在inserted 中,inserted 也是只调用一次。注意: 在v-指令名=" "中传入数据,要使用自定义指令传入的数据须要从binding.value 中获取。