我是 Vue 的初学者,我正在尝试了解如何使用自定义组件。我有一个简单的 Vue 应用程序,如下所示:
。.html
<div id="app1">
<button
v-for="(button, index) in buttons"
v-bind:key="button"
v-on:click="buttonClick(index)"
>
{{ button }}
</button>
</div>
。.js
const app1 = new Vue({
el: '#app1',
data: { buttons: ['A', 'B', 'C', ] },
methods: { buttonClick: (i) => console.log(i) },
})
单击按钮时,其相应的索引将记录到控制台。
我想通过制作自定义按钮组件来重构它,所以我试图将其更改为以下内容
.html (*
是 更改行(
<div id="app2">
<custom-button
v-for="(button, index) in buttons"
v-bind:key="button"
v-on:click="buttonClick(index)"
* v-bind:content="button",
>
{{ button }}
</custom-button>
</div>
。.js
Vue.component('custom-button', {
props: ['content'],
template: '<button> {{ content }} </button>'
})
(该应用程序保持不变,除了'#app1'
现在'#app2'
(单击这些按钮时,不会调用任何函数(按钮甚至没有事件侦听器(。所以这种方法显然行不通,所以我想知道正确的方法是什么?
(理想情况下,如果可能的话,我希望该方法保留在应用程序上。
在自定义组件上使用本机事件时,需要native
事件修饰符:
<div id="app2">
<custom-button
v-for="(button, index) in buttons"
v-bind:key="button"
* v-on:click.native="buttonClick(index)"
v-bind:content="button",
>
{{ button }}
</custom-button>
</div>
这是解释此功能的文档页面。