[Vuejs]-How to run a specific function if the component has been called by a specific component and not by other components in Vue?

2👍

There are a number of ways to accomplish this, the two that come to mind immediately use props.

  1. You could pass a filterDiagnoses boolean prop to select-diagnosis. If it’s true, run the filter logic.
<select-diagnosis v-model="form.diagnosis_dimission" :defaultValue="_.get(record, 'clean_diagnosis_dimission')" :filterDiagnoses="true" />
  1. You could invert control to the parent function and expose a filterFn callback prop – the parent function passes a function prop to the child that the child will call upon fetching the diagnoses (this feels cleaner and more extensible):
/* in the PtdTreatment component */
/* ... */
methods: {
  filterDiagnosis(data) {
    // filter data
  },
}

/* in the PtdTreatment template */
<select-diagnosis v-model="form.diagnosis_dimission" :defaultValue="_.get(record, 'clean_diagnosis_dimission')" :filterFn="filterDiagnosis" />

/* in the select-diagnosis component */
fetchDiagnosis(query) {
  const valid = query !== "" && query.length > 2;
  if (!valid) return;
  this.loadingSelect = true;
  let params = { string: query };
  axios
    .get("/config/diagnosis", { params })
    .then(({ data }) => {
      if (this.filterFn) {
        this.items = this.filterFn(data);
      } else {
        this.items = data;
      }
    })
    .finally(() => (this.loadingSelect = false));
  },
}

1👍

You can set a prop on the child component which specifies the ‘identity’ of the parent component, then test for that in the child:

<select-diagnosis
  v-model="form.diagnosis_dimission"
  :defaultValue="_.get(record, 'clean_diagnosis_dimission')"
  parent="PtdTreatment"
/>

Then in the child (simplified example):

export default {
    props: ["value", "defaultValue", "parent"],
    methods: {
        fetchDiagnosis(query) {
          if (this.parent === "PtdTreatment") {
            // Parent-specific code here
          }
        }
    }
}
👤match

Leave a comment