简体   繁体   中英

How to reload data from a component in Vue?

I have App.vue component and its child ItemsList.vue . In App.vue I have this:

export default {
    name: 'App',
    components: {
        ItemsList
    },
    data() {
        return {
            items_list: [
                getRandomItem(),
                getRandomItem(),
                getRandomItem(),
            ]
        }
    }
}

The data is an array of randomly generated items of the same structure. I want to return a new array of newly generated items when clicking a button but as I see, data() method is being called only once on start and then return just what was generated at the moment.

How do I rerun this method to return a new dataset?

The data() method is called only once when the instance of the component is created. It's a bit like a lifecycle hook.

You can use a function to generate a new array and replace the items_list of the component

data () {
  return {
    items_list: []
  }
},
methods {
  newList () {
    this.items_list = [
      getRandomItem(),
      getRandomItem(),
      getRandomItem(),
    ]
  }
},
mounted () {
  this.newList()
}

Documentation

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