Vue v-on:click在组件上不起作用

JavaScript

Stafan神乐

2020-03-09

我正在尝试在组件内部使用on click指令,但它似乎不起作用。当我单击该组件时,应该在控制台中单击“测试”,什么也没有发生。我在控制台中看不到任何错误,所以我不知道我在做什么错。

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vuetest</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

应用程序

<template>
  <div id="app">
    <test v-on:click="testFunction"></test>
  </div>
</template>

<script>
import Test from './components/Test'

export default {
  name: 'app',
  methods: {
    testFunction: function (event) {
      console.log('test clicked')
    }
  },
  components: {
    Test
  }
}
</script>

Test.vue(组件)

<template>
  <div>
    click here
  </div>
</template>

<script>
export default {
  name: 'test',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

第334篇《Vue v-on:click在组件上不起作用》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
理查德Itachi 2020.03.09

如果要侦听组件根元素上的本机事件,则必须对.native修饰符使用v-on,如下所示:

<template>
  <div id="app">
    <test v-on:click.native="testFunction"></test>
  </div>
</template>

或简而言之,如评论中所建议,您也可以执行以下操作:

<template>
  <div id="app">
    <test @click.native="testFunction"></test>
  </div>
</template>

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android