0

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?

2
  • You don't really re-run it. Are you trying to update it? Data is the initial state of an instance of your component. You change it through the components setters. Commented Jul 29, 2020 at 14:45
  • you may interesting in watch property vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property (or direct set items_list when button clicked like @zero298 said) Commented Jul 29, 2020 at 14:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.