vueJS 2,如何动态地将 JavaScript 绑定到组件



>模板

<template v-for="(item, i) in items">
<v-divider
v-if="item.divider"
class="my-4"
:key="i"
></v-divider>
<v-list-tile
:key="i"
v-else
:to="item.to"
>
<v-list-tile-action>
<v-icon>{{ item.icon }}</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title>
{{ item.text }}
</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</template>

脚本部分:

export default {
name: 'sideMenu',
data () {
return {
toggleKeyboardShortcuts: false,
items: [
{ icon: 'add', text: 'Create new question', to: '/question' },
{ divider: true },
{ icon: 'lightbulb_outline', text: 'Notes', to: '#' },
{ icon: 'touch_app', text: 'Reminders', to: '#' },
{ divider: true },
{ icon: 'settings', text: 'Settings', to: '#' },
{ icon: 'help', text: 'Help', to: '#' },
{ icon: 'keyboard', text: 'Keyboard shortcuts', events: { 'click': this.toggleKeyboardShortcutsDialog.bind(this) } },
{ icon: 'phonelink', text: 'App downloads', to: '#' }
]
}
},... more stuff, but not relevant for this question

我能够传递不同的属性并且事物正确呈现,但是传递一个 JavaScript 函数在单击此列表的项目时执行会惨败。我需要这种行为来触发对话框(使用路由器访问页面有效(

@click是您想要的触发器,但@click只能调用组件中定义的方法。

因此,快速脏将是接受 Items 数组的索引值的方法内部函数,然后从方法内部调用所需的实际函数。

我写了一支快速的笔,因为我的解释令人困惑:https://codepen.io/anon/pen/QMpgGN?editors=1111

.html:

<div id="app">
<template>
<button v-for="(o, i) in items" @click="dynamicFunc(i)">
{{ o.text }}
</button>
</template>
</div>

js:(没有 vue-loader(

new Vue({
el: '#app',
data() {
return {
items: [
{
text: "test",
click: function() {alert("hi~")}
}
]
}
},
methods: {
dynamicFunc(i) {
this.items[i].click()
}
}
})

最新更新