data(){
return {
items:[1,2,3,4,5]
}
},
directives:{
attack:el=>{
console.log(this)
setInterval(()=>{
el.style.background = '#' + Math.floor(Math.random()*16777215).toString(16)
},500)
setTimeout(()=>{
this.items.pop()
},10000)
}
}
今天在directives中发现this指向undefinded,filters中也是如此;写filters时我将data中的数组写在filters里解决了问题,但是写directives时不能这么做,AI告诉我:
directives: {
attack: el => {
console.log(this); // 这里的this不会指向Vue实例,因为它是在全局作用域中定义的箭头函数
setInterval(() => {
el.style.background = '#' + Math.floor(Math.random() * 16777215).toString(16);
}, 500);
setTimeout(() => {
// 假设这里的this应该指向Vue实例
// 因为箭头函数不绑定自己的this,它会捕获其所处上下文的this值
// 但是由于这个函数是在directives对象里而不是Vue方法或生命周期钩子中定义的,所以这个this不会如你所愿
// 如果需要操作Vue实例,需要另外的方式来传递Vue实例的引用进来
this.items.pop();
}, 10000);
}
}
之后它告诉我:通过绑定的方式传递数据或方法是一种常见的解决方案。代码修改后:
<div class="test_area">
<span v-attack:popItems="popItems" v-for="index in items" :key="index">+</span>
</div>
methods:{
popItems() {
this.items.pop();
},
createAtk() {
}
},
data(){
return {
items:[1,2,3,4,5]
}
},
directives:{
attack:(el,binding)=>{
const method = binding.value
setInterval(()=>{
el.style.background = '#' + Math.floor(Math.random()*16777215).toString(16)
},500)
setTimeout(()=>{
method()
},10000)
}
}
通过指令的参数 v-attack:popItems
将 Vue 实例中的 popItems
方法传递给了指令。指令在需要的时候调用了这个方法,实现了操作 Vue 实例的目的。