vue.js - 如何使用 vue getter 查找对象内的值?

标签 vue.js vuex

我想获取vuex状态内对象的特定值。

让我告诉你我的意思:

import { createStore } from "vuex";

export default createStore({
    state: {
        cards: [{
                title: "Blog 1",
                htmlCode: "This is blog 1",
                index: 1,
            },
            {
                title: "Blog 2",
                htmlCode: "This is blog 2",
                index: 2,
            },
            {
                title: "Blog 3",
                htmlCode: "This is blog 3",
                index: 3,
            },
            {
                title: "Blog 4",
                htmlCode: "This is blog 4",
                index: 4,
            },
            {
                title: "Blog 5",
                htmlCode: "This is blog 5",
                index: 5,
            },
            {
                title: "Blog 6",
                htmlCode: "This is blog 6",
                index: 6,
            },
            {
                title: "Blog 7",
                htmlCode: "This is blog 7",
                index: 7,
            },
        ],
    },
    getters: {
      getTodoById: (state) => (id) => {
        return state.cards.find(todo => todo.index === id)
      }
    },
    mutations: {},
    actions: {},
    modules: {},
});

现在,如果我在代码中插入这个值:<p>{{ this.$store.getters.getTodoById(2) }}</p> ,我得到这个结果:{ "title": "Blog 2", "htmlCode": "This is blog 2", "index": 2 } 我想要的是例如 htmlCode 的值结果将是 This is blog 2 .

希望有人能明白我的意思。

为了清楚起见:我希望在浏览器中得到这个结果:这是博客 2

对于我的网站来说,使用 vuex getters 完成非常重要。

最佳答案

这是一个可能的解决方案

getTodoById: (state) => (id) => {
  const todo = state.cards.find(todo => todo.index === id)
  return todo.htmlCode
}

其他解决方案是在组件中创建一个 todo 数据,并在 created() 中添加 getter 并分配给该数据。

  data() {
    return {
      todo: null,
    };
  },
  created() {
    this.todo = this.$store.getters.getTodoById(id) // for example extracted by the route
  },
<p>{{ todo.htmlCode }}</p>

关于vue.js - 如何使用 vue getter 查找对象内的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70199322/

相关文章:

将 css 类分配给 textArea 时出现 Javascript 错误

javascript - Nuxt.js:方法中的迭代会导致问题

javascript - 如何在 MaterializeCSS 中将颜色绑定(bind)到卡片

vue.js - 如何重用应该使用唯一 vuex 存储实例的组件

javascript - Vuex with Jest - 无法读取未定义的属性 <getterName>

vue.js - 基于子组件的计算属性

javascript - 我可以使用计算属性来有条件地设置表格行的样式吗?

javascript - 如何避免 Vue.JS/Axion 返回未定义而响应代码为 200?

vue.js - 如何在 vue.js 2 的其他组件中调用方法?

javascript - 如何使用 Vuex 操作中的 vue 路由器进行导航