简体   繁体   中英

vueJS 2, how to bind javascript to a component dynamically

Template :

<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>

Script section:

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

I'm able to pass different attributes and things are properly rendering, but passing a JavaScript function to execute when an item of this list if clicked fails miserably. And I need this behavior to trigger a Dialog (accessing pages using router works)

@click is the trigger you want, but @click can only call methods defined in the component.

so a quick an dirty would be a function inside method that accepts the index value of the items array, and then from inside the method, call the actual function you want.

i wrote a quick pen because my explanation is confusing: 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: (without vue-loader)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM