如何通过将方法名称通过变量传递给@click来绑定方法

时间:2018-10-16 16:31:28

标签: javascript vue.js vuejs2 vuetify.js

我还是vuejs的新手,当我想到一个问题时,我正在观看许多在线视频以自学。

使用vuetify,我构建了一个导航抽屉,该菜单在菜单项列表中循环(v-for),并使用v-if打印项的详细信息。

现在我有一个问题: 在vuejs中,有一种方法可以通过向方法传递变量来将方法从df.index=df.index%3+1 df.set_index('A',append=True,inplace=True) newdf=df.unstack(level=0) newdf.columns=newdf.columns.map('{0[0]}_{0[1]}'.format) newdf Out[291]: B_1 B_2 B_3 C_1 C_2 C_3 A a 1 0 0 1 0 1 b 0 1 0 0 0 1 c 1 1 1 1 0 0 之类的vue“方法”绑定到singOut()

@click@click="item.method"对我不起作用。

澄清:我想绑定到@click="{item.method}"的方法可能比singOut()多。因此,我正在寻找一种更动态的方法来绑定该方法。

预先感谢:)

@click
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;
}

2 个答案:

答案 0 :(得分:1)

Codepen

在方法名称和参数属性中分割方法。 例如,您可以创建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)
  },

根据需要进行自定义声明。
这种方法有什么缺陷吗?

答案 1 :(得分:0)

由于您的std::time_t t = 0; std::cout << -1 * std::mktime(std::gmtime(&t)); 中已经有singOut(),因此您的HTML中的methods: {}就是@click

您的@click="singOut(item.method)"必须能够接受这些参数。

singOut()

我认为这不是您想要实现的,因为对象中的方法由函数组成。

使用当前数据:

singOut(method) {
  // method here
  console.log(method)
}

我建议你可以做的是

  • 具有另一个属性items: [ { icon: 'help', text: 'Help', method: 'Some method here', alert: 'Really want to delete?' } ] 并为其设置字符串。
  • alert事件绑定到以该项目作为参数的方法;使用该方法触发其中具有@click属性值的alert()

示例:

alert