我想获取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/