如何在 Vue 中使用 v-for 传递函数的参数?

How to pass parameter of a function with v-for in Vue?

我正在尝试通过使用 v-for 遍历数组项来将参数传递给函数。

<template>
  <v-app>
    <v-app-bar app>
      <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
      <v-spacer></v-spacer>
      <h1 ref="y"></h1>
    </v-app-bar>
    <v-content>
      <router-view />
      <v-navigation-drawer v-model="drawer" class="x">
        <v-list-item
          v-for="item in items"
          :key="item.unidade"
          :to="item.link"
          :@click="change(item.method)"
        >{{item.unidade}}</v-list-item>
      </v-navigation-drawer>
    </v-content>
  </v-app>
</template>

<script>
export default {
  name: "App",

  data: () => ({
    items: [
      { unidade: "IPE", link: "/ipe", method: "IPE" },
      { unidade: "DCSI", link: "/dcsi", method: "DCSI" },
      { unidade: "RT", link: "/rt", method: "RT" }
    ],
    drawer: false
  }),
  methods: {
    change(val) {
      console.log(val);
      this.$refs.y.innerText = val;
    }
  }
};
</script>
<style lang="stylus" scoped>
.x {
  position: absolute;
}
</style>

我希望将 items 数组中的参数传递给 change(val) 方法,为每个 v-list-item 提供一个不同的事件侦听器。 然后我希望 h1 和 ref="y" 根据我点击的 v-list-item 更改它的文本。但到目前为止,我收到浏览器错误 "Error in render: "TypeError: Cannot set 属性 'innerText' of undefined""

您可以将 innerText 绑定到反应变量,而不是设置 <h1> 的 innerText。您可以在数据中创建一个可以存储所选方法的变量,然后使用 {{}} 语法将其绑定到 innerText。这样做会更符合 Vue 最佳实践。让我告诉你我的意思。

<template>
  <v-app>
    <v-app-bar app>
      <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
      <v-spacer></v-spacer>
      <h1 ref="y">{{ selectedMethod }}</h1> 
    </v-app-bar>
    <v-content>
      <router-view />
      <v-navigation-drawer v-model="drawer" class="x">
        <v-list-item
          v-for="item in items"
          :key="item.unidade"
          :to="item.link"
          :@click="change(item.method)"
        >{{item.unidade}}</v-list-item>
      </v-navigation-drawer>
    </v-content>
  </v-app>
</template>

<script>
export default {
  name: "App",

  data: () => ({
    items: [
      { unidade: "IPE", link: "/ipe", method: "IPE" },
      { unidade: "DCSI", link: "/dcsi", method: "DCSI" },
      { unidade: "RT", link: "/rt", method: "RT" }
    ],
    selectedMethod: '', // Initially blank
    drawer: false
  }),
  methods: {
    change(val) {
      this.selectedMethod = val; // Update the value of selectedMethod
    }
  }
};
</script>
<style lang="stylus" scoped>
.x {
  position: absolute;
}
</style>

希望对您有所帮助!