簡體   English   中英

從外部重新加載 vue 組件

[英]reload vue component from outside

我有一個 laravel vue 項目,它顯示組件中的項目列表。 安裝后的組件會調用 ajax 來填充數據元素。 但是,頁面上還有其他項目(不在 vue 中)可以將元素添加到數據庫中,我想確保列表在組件中是反應性的。

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

當用戶執行將任務添加到列表的操作時,有沒有辦法從組件外部觸發組件上的getTasks方法?

您可以在安裝組件時聲明一個全局 function(綁定到 Vue 組件的上下文):

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

然后你可以在調用getTasks()windows.getTasks()之外使用它

您應該使用 vuex 操作。

這是一個例子:

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)
    }
  }
})

完整來源:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM