用this的写法和不用this的写法
代码示例1
new Vue({
data:function(){
return{
n:0,
array:[1,2,3,4,5,6,7,8]
}
},
template:`
<div class="red">
{{n}}
<button @click="add">+1</button>
<hr>
<!-- {{filter(array)}}-->
<!-- 不用this的写法-->
{{filter()}}
<!-- this写法-->
</div>
`,
methods:{
add(){
this.n +=1
},
// filter(array){
// return array.filter(i => i % 2 ===0)
// },//不用this的写法
filter(){
return this.array.filter(i => i % 2 ===0)
}//this的写法
},
// render(h) {
// return h(demo);
// },
}).$mount("#frank")
代码示例2
let data2 = {};
data2._n = 0; // _n 用来偷偷存储 n 的值
Object.defineProperty(data2, "n", {
get() {
return this._n;//this的写法
return data2._n;//不用this的写法
},
set(value) {
if (value < 0) return;//如果value小于0,就什么都不做
this._n = value;//如果value大于等于0,就把value写入this._n/或者说,把this._n的值设置为新的值value。
}
});
this就是用来代指没有命名的新对象{}