【发布时间】: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 }}?我可能会解决模板中没有这些不可读代码的问题,并创建一个方法或计算属性,而不是只返回标题。