Jim E Russel
Jim E Russel

Reputation: 495

vue.js - call component method from another component

I want to use the getProjects() method of Component 2 to refresh my table after adding a data. Both of these components are attached in a blade.php

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

Component 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);
      });
    },

Upvotes: 2

Views: 5428

Answers (2)

Suoakira
Suoakira

Reputation: 101

yes it is possible. Step 3 will do what you explicitly asked but there are better ways.

Three ways.

1) VUEX: Move the method you wish to call, to Vuex and any associated reactive data properties to the store. And use getters to retrieve the updated data.

2) MIXINS: With mixins you would move your component2.vue and associated data properties to a mixin, and import it in both components, allowing it to be called from each.

3) Hacky fix that actually calls the method from another component (not best practice)

You can mount methods to $root and call them from another component, by emiting a event. Using your example it would look like the following.

Components2.vue // mount the method you wish to call


// new code
  mounted() {

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

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


Component1.vue // call the mounted method

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


more info here How can I call method in other component on vue.js 2? in case i made any typos

Upvotes: 3

Marvin
Marvin

Reputation: 71

You should use vuex. See https://medium.com/js-dojo/vuex-2638ba4b1d76

You call the vuex action from your component and in this action, you can make the axios call directly or use another service to make your api calls.

Mutations should never be called from components only from actions inside the store.

kind regards

Upvotes: 4

Related Questions