gpt4 book ai didi

javascript - VUE-指令中的事件监听器无法读取方法中定义的函数

转载 作者:行者123 更新时间:2023-12-02 20:54:42 25 4
gpt4 key购买 nike

我希望在“方法”中定义的函数在以下情况下执行我的元素被点击。但是,我的事件监听器仅在我使用匿名函数(例如

)时才执行某些操作
el.addEventListener('click' function() {console.log('hi'))

当我在方法中设置函数时,它会发出错误消息

vue.js?3de6:634 [Vue warn]: Error in directive myDirective bind hook: "ReferenceError: sizechange is not defined"

found in

---> at /Users/soonkpaik/Downloads/Start 2/src/App.vue my code is as below.

<template>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<h1 v-myDirective:sizechange='{ inisize:100, finsize:500, color:"pink", blinkcolor:"red" }'>Directives Exercise!</h1>
<!-- Exercise -->
<!-- Build a Custom Directive which works like v-on (Listen for Events) -->

</div>
</div>
</div>
</template>

<script>
export default {
directives:{ myDirective:{
bind(el,binding,vnode){




let maincolor=binding.value.color;
let newcolor=binding.value.blinkcolor;
let currentcolor=maincolor;

setInterval( ()=>{
currentcolor==newcolor? currentcolor=maincolor : currentcolor=newcolor

el.style.backgroundColor=currentcolor
},500)

el.addEventListener('click',sizechange)






}

}
},
methods:{

sizechange() {
console.log('hi')

}
},
}
</script>

<style>
</style>

我做错了什么??预先感谢您。

最佳答案

这里的问题是 sizechange() 函数无法直接在 bind hook function 内部访问直接地。您需要引用当前的vnode上下文如:

export default {
directives: {
myDirective: {
bind(el, binding, vnode) {

// Your logic here...

var vm = vnode.context;
el.addEventListener('click', vm.sizechange) // This works fine now
}
}
},
methods: {
sizechange() {
console.log('hi')
}
},
}

关于javascript - VUE-指令中的事件监听器无法读取方法中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com