我正在尝试在组件内使用 on click 指令,但它似乎不起作用。当我单击组件时,当我应该在控制台中获得“单击测试”时,什么都不会发生。我在控制台中没有看到任何错误,所以我不知道我做错了什么。
索引.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>
应用程序.vue
<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>
原文由 Javier Cárdenas 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果你想在组件的根元素上监听原生事件,你必须对
v-on
使用 .native 修饰符,如下所示:或者简而言之,正如评论中所建议的,您也可以这样做:
参考阅读更多关于 原生事件