vue中点击时如何绑定上下文?

问题描述 投票:0回答:1

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() {
            // ...
        }
    }
}

有什么想法吗?

javascript vue.js this
1个回答
0
投票

默认情况下,左键点击会触发

@click
事件,右键会触发
@contextmenu
事件,所以和原生 JavaScript 类似,只需要声明事件发生时要执行的函数即可。

methods
部分,您在对象内声明函数,因此您只需在函数之间使用逗号而不是分号。另外,请遵循我演示的功能模式,但您也可以参考随附文档中的示例。

您展示的示例代码根据其外观遵循选项 API 的结构。因此,我将在我的回复中相应地提供示例代码。

选项 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>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.