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

Adding and reading json data stored in vuex

我有一个 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-for

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

我无法显示任何数据,我也没有错误。如何显示vuex中保存的数据?

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

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 = '';
},

您可以创建一个 computed 属性,returns 一个列表中的对象解析为 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>

Note: Since ids are not unique in your example, you can use an index in v-for as the key. Also, to show the first name, you need to use the user object.

另一种解决方案:在store中解析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);