繁体   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