简体   繁体   中英

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.

<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.

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. What you could do is set the json to a reactive property and check for changes on there. When changing the JSON you also need to update the reactive property so the watcher gets triggered

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.

I solve this issue with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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