首页 > 解决方案 > 如何在 Vue 的渲染列表中存储特定项目的数据属性值

问题描述

我正在尝试在 Vue 的列表项上创建一个关注按钮。我的策略是获取特定列表项属性的值并将其存储在数据对象中。然后在方法中使用此值将其添加到我的数据库中的数组中。

      <div v-for="result in results" :key="result.symbol">
        {{ result.name }}
        <button @click="followStock">+follow</button>
      </div>

我不确定如何将 result.symbol 的值“放入”按钮元素以在下面的数据对象中设置值符号。

<script>

export default {
  data() {
    return {
      results: [ // this is populated by an api call
                {
                 currency: "USD"
                 exchangeShortName: "NYSE"
                 name: "International Game Technology PLC"
                 stockExchange: "NYSE"
                 symbol: "IGT"
                },
                {...},
                ...
               ],
      symbol: "",
    };
  },
  
    followStock() {
      // add this.symbol to database array
    },
  },
};
</script>

我猜我可能会忽略一个更简单的策略,因为我还是 Vue 的新手,所以任何其他基本上允许我将 result.symbol 的值从任何渲染结果发送到我的数据库的解决方案都会很棒.

标签: javascriptvue.js

解决方案


您可以将结果作为参数传递给您的方法。

<div v-for="result in results" :key="result.symbol">
    {{ result.name }}
    <button @click="followStock(result)">+follow</button>
</div>

在你的方法中:

methods: {
    followStock(result) {
        // do something with result
        console.log({result});
        let symbol = result.symbol;
    },
}

PS 我没有看到您将 followStock() 放入methods对象中,但我在示例中这样做了。https://vuejs.org/v2/api/#methods


推荐阅读