vue 中点击时如何绑定上下文?
具有点击功能的Html:
<li v-on:click="itemClick($event, this)"></li>
我的vue js代码:
var app = new Vue({
el: '#mainApp',
methods: {
itemClick: (event, context) => {
context.someFunction(); // undefined
this.someFunction(); // undefined
};
someFunction: function() {
// ...
}
}
}
有什么想法吗?
默认情况下,左键点击会触发
@click
事件,右键会触发 @contextmenu
事件,所以和原生 JavaScript 类似,只需要声明事件发生时要执行的函数即可。
methods()
-Vue 文档在
methods
部分,您在对象内声明函数,因此您只需在函数之间使用逗号而不是分号。另外,请遵循我演示的功能模式,但您也可以参考随附文档中的示例。
您展示的示例代码根据其外观遵循选项 API 的结构。因此,我将在我的回复中相应地提供示例代码。
<template>
<div>
<li @click="(event) => itemClick(event)">Test</li>
</div>
</template>
<script>
export default {
methods: {
itemClick(event) {
// context.someFunction(); // this doesn't make sense
this.someFunction(); // call methods.someFunction()
}, // <--- need use , instead of ; because methods is object, where itemClick() and someFunction() functions will elements of object
someFunction() {
// ...
}
}
}
</script>