This is the 7th day of my participation in the August Text Challenge.”August More Challenge”

Sometimes you use axios in vue and use data variables to store the retrieved data, but the function is in Mounted, but it still doesn’t render on the page.

Here’s an example.

<li v-for="(item, index) in re" :key="index"> {{item}} </li> export default { data() { return { res:[], re:[], }; }, methods: { get(}{ let that = this; axios .get("/api/test", { params: {}, }) .then(function (response) { that.res=response.data; for(let i in that.res) that.re[i]=that.res[i].name; }}Copy the code

Here there is no render data in the browser, we print the RE and find that the RE has data, but it does not render. This is because of vUE’s array update detection mechanism. Vue cannot detect changes to the following arrays:

  1. When you set an array item directly using an index, for example:vm.items[indexOfItem] = newValue
  2. When you modify the length of an array, for example:vm.items.length = newLength

Here’s an example:

Var vm = new Vue({data: {items: ['a', 'b', 'c']}}) vm.items[1] = 'x' // not responsive vm.items. Length = 2 // Not responsiveCopy the code

To solve the first type of problem, the following two methods can achieve the same effect as vm.items[indexOfItem] = newValue, and also trigger status updates within a responsive system:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
Copy the code
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
Copy the code

You can also use the vm.$set instance method, which is an alias for the global method vue. set:

vm.$set(vm.items, indexOfItem, newValue)
Copy the code

To solve the second type of problem, you can use Splice:

vm.items.splice(newLength)
Copy the code

You can also use these methods: Vue wraps the change methods of the array being listened on, so they will also trigger view updates. These covered methods include:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

Modify the above code:

for(let i in that.res)
   that.re.push(that.res[i].name);
Copy the code

Here the page data can be rendered.