简体   繁体   中英

reload vue component from outside

I have a laravel vue project that displays a list of items in a component. The component when mounted makes an ajax call to populate the data element. However, there's other items on the page (not in vue) that can add elements to the database, and I'd like to make sure the list is reactive in the component.

mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}

When the user does an action that would add a task to the list, is there a way to fire the getTasks method on the component from outside the component?

You can declare a global function (binding context to Vue component) when component is mounted:

mounted() {
  windows.getTasks = this.getTasks.bind(this);
  this.getTasks();
},

Then you can use it outside calling getTasks() or windows.getTasks()

You should use vuex actions.

Here's an example:

Vue.component('ChildB',{
  template:`
    <div class="child childB">
      <h1> Score: {{ score }} </h1>
      <button @click="changeScore">Change Score</button>
    </div>`,
  computed: {
    score () {
      return this.$store.getters.score
    }
  },
  methods: {
    changeScore () {
      this.$store.dispatch('incrementScore', 3000)
    }
  }
})

full source:

https://codepen.io/tutsplus/pen/MXpPLz

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