我对 vuejs 还很陌生,正在观看许多在线视频之一来自学,这时我想到了一个问题。
使用 vuetify,我构建了一个抽屉导航,它循环 (v-for) 菜单项列表并使用 v-if 打印项目的详细信息。
现在我的问题是:
在 vuejs 中,有没有一种方法可以通过传递带有变量的方法来将 vues“方法”(如 singOut()
)中的方法绑定(bind)到 @click
。
@click="item.method"
和 @click="{item.method}"
对我不起作用。
澄清:可能有比 singOut()
更多的方法,我想绑定(bind)到 @click
。因此,我正在寻找一种更动态的方式来绑定(bind)该方法。
提前致谢:)
new Vue({
el: '#app',
data: {
items: [
{ icon: "lightbulb_outline", text: "Notes", path: '/tools/notes' },
{ icon: "access_alarm", text: "Worktime", path: '/tools/worktime' },
{ divider: true },
{ heading: "Labels" },
{ icon: "add", text: "Create new label" },
{ divider: true },
{ heading: "Account" },
{ icon: "lock_open", text: "Login", path: '/signin' },
{ icon: "mdi-account-plus", text: "Sign Up", path: '/signup' },
{ icon: "mdi-logout", text: "Sign Out", method: 'singOut()' },
{ divider: true },
{ icon: "settings", text: "Settings", path: '/' },
{ icon: "chat_bubble", text: "Trash", path: '/' },
{ icon: "help", text: "Help", method: 'sendAlert("Really want to delete?")' },
{ icon: "phonelink", text: "App downloads", method: 'sendAlert("Leaving the app")' },
{ icon: "keyboard", text: "Keyboard shortcuts", path: '/' }
]
},
methods: {
navigateTo(path) {
if (path) {
this.$router.push(path);
} else {
this.$router.push('/');
}
},
singOut(){
this.$store.dispatch('singOut');
},
sendAlert(msg) {
alert(msg);
}
}
});
ul {
list-style: none;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="(item,i) in items">
<span v-if="item.heading" :key="i"><b>{{item.heading}}</b></span>
<span v-else-if="item.divider" :key="i">--------</span>
<span v-else-if="item.method" @click="item.method" :key="i" style="cursor:pointer;">{{item.text}} (+ @click->Method)</span>
<span v-else> {{item.text}} -> {{item.path}}</span>
</li>
</ul>
</div>
最佳答案
在方法名称和参数属性中拆分方法。
您可以创建例如 call
方法,该方法使用传递的参数调用传递的函数 @click="call(item.method, item.args)"
。
<v-btn v-for="item in items" :key="item.id" @click="call(item.method, item.args)">
{{item.text}}
</v-btn>
items: [
...
{ id: 5, text: "5", method: "methodTwo", args: ["Another message", 123] },
methods: {
call(method, args = []) {
this[method](...args)
},
根据需要进行自定义断言。
这种方法有什么缺陷吗?
关于javascript - 如何通过变量将方法名称传递给@click来绑定(bind)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52840096/