directives,filters等中this指向问题

    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 实例的目的。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值