vue.js-从另一个组件调用组件方法

时间:2019-12-12 07:38:54

标签: javascript laravel vue.js

我想在添加数据后使用组件2的getProjects()方法刷新我的表。这两个组件都附加在blade.php中

组件1.vue

 methods: {
  addData() {
    this.attemptSubmit = true;
    this.validate = true;
    this.errors = [];
    if (this.errors) event.preventDefault();
    axios
    .post('/api/department', {
                department: this.department,
                section: this.section
    })
    .then(response => {
      this.validate = false;
      this.department = '';
      this.section = '';
      this.errors = '';
      this.output = response.data;
      //--- I want to insert the getProjects() method here 
    })
    .catch(error => this.errors = error.response.data.errors)
  },

组件2.vue

methods: {
    getProjects(url = '/api/departments') {
      this.tableData.draw++;
      axios
      .get(url, {params: this.tableData})
      .then(response => {
        let data = response.data;
        if (this.tableData.draw == data.draw) {
          this.projects = data.data.data;
          this.configPagination(data.data);
        }
      })
      .catch(errors => {
        console.log(errors);
      });
    },

2 个答案:

答案 0 :(得分:2)

您应该使用vuex。参见https://medium.com/js-dojo/vuex-2638ba4b1d76

您从组件调用vuex操作,在此操作中,您可以直接进行axios调用,也可以使用其他服务进行api调用。

永远不要仅通过商店内部的操作从组件中调用突变。

亲切的问候

答案 1 :(得分:1)

是的,有可能。步骤3将执行您明确要求的操作,但是有更好的方法。

三种方式。

1) VUEX::将要调用的方法移至Vuex,并将所有关联的反应数据属性移至存储。并使用吸气剂来检索更新的数据。

2) MIXINS:使用mixin,您可以将component2.vue和关联的数据属性移动到mixin,然后将其导入两个组件中,从而可以从每个组件中调用它。

3)错误修复,它实际上是从另一个组件调用该方法的(不是最佳实践)

您可以将方法挂载到$ root并通过发出事件从另一个组件中调用它们。以您的示例为例。

Components2.vue //挂载您要调用的方法


// new code
  mounted() {

    this.$root.$on("getProjects", () => {

      return this.getProjects(url = '/api/departments');
    });
  }


Component1.vue //调用已安装的方法

 methods: {
   // new code
    emitGetProjects() {
     this.$root.$emit("getProjects") //like this
    }
  },


更多信息在How can I call method in other component on vue.js 2?,以防万一我有错字