【问题标题】:How to use vue getters to find a value inside an object?如何使用 vue getter 在对象中查找值?
【发布时间】:2022-01-08 22:29:10
【问题描述】:

我想在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 getter 完成对我的网站来说非常重要。

【问题讨论】:

  • 您是否尝试过通过点符号访问标题? {{ $store.getters.getTodoById(2).title }} ?我可能会解决模板中没有这些不可读代码的问题,并创建一个方法或计算属性,而不是只返回标题。

标签: vue.js vuex


【解决方案1】:

这是一个可行的解决方案

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>

【讨论】:

  • find 可能会返回 null。也许返回 todo?.htmlCode ?? '' 或其他东西。
  • 是的或模板中的v-cloakv-if="todo"
【解决方案2】:

这应该可行。

<p>{{ this.$store.getters.getTodoById(2).htmlCode}}</p>

【讨论】:

  • 他们想输出htmlCode,而不是index
猜你喜欢
  • 2019-12-12
  • 1970-01-01
  • 2011-11-07
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多