添加和读取存储在vuex中的json数据



我有一个vuex存储,我正在添加一些josn数据,这就是格式。

[
{
"id":1,
"firstname": "toto",
"lastname": "titi"
},
{   "id":2,
"firstname": "one",
"lastname": "two"
}
]

我正在添加点击操作的数据,这是的操作方法

addLink: function() {
var dt = '[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]';
this.ADD_LINK(dt)
this.newLink = '';
},

数据被添加到存储中,我可以像这个一样访问它

computed: {
users(){
return this.countLinks;
}
}

我可以用这种方式显示数据{{users}},并且它正在被显示。这是因为我点击了两次并添加了两次json。

[ "[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]", "[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]" ]

然而,当我尝试将v-用于时

<ul id="users">
<li v-for="user in users" :key="user.id">
{{ users.firstname}}
</li>
</ul>

我不能显示任何数据,我没有错误。如何显示保存在vuex中的数据?。

您可以创建一个computed属性,该属性返回一个列表中解析为JSON:的对象

new Vue({
el:"#app",
data: () => ({
users: [ "[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]", "[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]" ]
}),
computed: {
usersList: function() {
return this.users.flatMap(userList => JSON.parse(userList));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul id="users">
<li v-for="(user, index) in usersList" :key="index">
{{ user.firstname}}
</li>
</ul>
</div>

注意:由于id在您的示例中不是唯一的,因此您可以使用v-for中的index作为key。此外,要显示名字,您需要使用user对象。

另一个解决方案:分析存储中的dt,并使用Array#concat将元素作为对象添加到初始列表中:

let countLinks = [
{ "id":1,  "firstname": "toto", "lastname": "titi" },
{ "id":2, "firstname": "one", "lastname": "two" }
];
function ADD_LINK(dt) {
countLinks = countLinks.concat(JSON.parse(dt));
}
const dt = '[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]';
ADD_LINK(dt);
console.log(countLinks);

您必须按原样存储数据,而不是转换为字符串

addLink: function() {
var dt = [
{
"id":1,
"firstname": "xx",
"lastname": "yy"
},
{
"id":2,
"firstname": "one",
"lastname": "two"
}
];
// remove the single quote from the above array
this.ADD_LINK(dt)
this.newLink = '';
},

如果您从外部源获取var dt,那么您应该考虑使用以下内容转换为有效的js-json格式:

addLink: function() {
var dt = '[{"id":1,"firstname":"xx","lastname": "yy"},{"id":2,"firstname": "one","lastname": "two"}]';
// parse it to json format
var parsedDt = JSON.parse(dt);
// add the `parsedDt`
this.ADD_LINK(parsedDt)
this.newLink = '';
},

最新更新