首页 > 解决方案 > 如何在 vuejs 中使用 axios 访问 json 文件?

问题描述

我的 data.json 中有以下内容存储在公用文件夹中:

[
 {
    "content1": "testing"
 }
]

在我的 Vuex 商店中,我有以下状态和突变:

state: {
  contents: []
},
mutations: {
  getContent1(state){
  axios
  .get("data.json")
  .then(response => (state.contents = response.data))
}

在我的组件中,我可以使用以下命令通过 ...mapState 查看我的文件:

<p> {{ contents }} </p>

但是,如果我要切换到,{{ contents.content1 }}我将无法再看到屏幕上的数据。关于发生了什么的任何提示?

其次,我希望使用 axios 更改 json 文件中的“content1”数据,我打算这样写:

putContent1(state) {
  axios
  .put("data.json")
  .then(response => state.contents = state.newContents))

// however, I am not quire sure the last line on the .then, on whether that is correct or not.

任何帮助,将不胜感激!

标签: vue.jsaxiosvuex

解决方案


推荐阅读