[英]vue.js - call component method from another component
我想在添加数据后使用组件 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);
});
},
你应该使用 vuex。 见https://medium.com/js-dojo/vuex-2638ba4b1d76
您从组件调用 vuex 操作,在此操作中,您可以直接进行 axios 调用或使用其他服务进行 api 调用。
绝不能仅从 store 内的操作中从组件中调用突变。
亲切的问候
对的,这是可能的。 第 3 步将执行您明确要求的操作,但有更好的方法。
三种方式。
1) VUEX:将您希望调用的方法移动到 Vuex 和任何关联的响应式数据属性到 store。 并使用 getter 来检索更新的数据。
2) MIXINS:使用 mixin,您可以将 component2.vue 和关联的数据属性移动到 mixin,并将其导入到两个组件中,允许从每个组件调用它。
3) 实际上从另一个组件调用方法的Hacky 修复(不是最佳实践)
您可以通过发出事件将方法挂载到 $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
}
},
更多信息在这里如何在 vue.js 2 上调用其他组件中的方法? 万一我打错了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.