简体   繁体   English

Vue.js - 观察 JSON 文件中的变化

[英]Vue.js - Watch changes in JSON file

Here idea is to watch changes made in JSON file and if some value is changed it automatically changes the condition v-if.这里的想法是观察 JSON 文件中所做的更改,如果某些值发生更改,它会自动更改条件 v-if。

<div id="app">
 <div v-if="content == 'one'">
   <p>Content one</p>
 </div>
 <div v-else-if="content == 'two'">
   <p>Contentn two</p>
 </div>
</div>

Now the tricky part comes, I need to be able after build to change the JSON file, and automatically to change what will be shown.现在棘手的部分来了,我需要能够在构建后更改 JSON 文件,并自动更改将显示的内容。

new Vue({
  el: "#app",
  data: {
   content: ''
  },
  methods: {
    // import of JSON and value that will assign value to this.content
        // Now value can be 'one' or 'two'
  }
})

Its not possible to watch for changes inside a json file.不可能观察 json 文件中的变化。 What you could do is set the json to a reactive property and check for changes on there.您可以做的是将 json 设置为反应属性并检查那里的更改。 When changing the JSON you also need to update the reactive property so the watcher gets triggered更改 JSON 时,您还需要更新响应属性,以便触发观察者

new Vue({
  el: "#app",
  data: {
   content: ''
  },
  watch: {
    content: function (val) {
      // do something when content has changed
    },
    },
  methods: {
    importJson() {
            // import json and set contents to content
    },
    saveJson(newJSON) {
        this.content = newJSON
      // Somehow save the json data to the json file
    }
  }
})

You should now that changes to a JSON file are not persistent.您现在应该对 JSON 文件的更改不是持久的。

I solve this issue with axios.我用 axios 解决了这个问题。 :) :)

methods: {
        updateData () {
          axios.get('../static/client/data.json').then(response => {
            console.log(response.data)
            this.dataClient = response.data
          })
        }
      },
      created () {
        this.updateData()
      }

Now when you change JSON file in 'dist' folder after build and refresh browser it will load new value.现在,当您在构建和刷新浏览器后更改“dist”文件夹中的 JSON 文件时,它将加载新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM