Vue中调用另一个组件中自定义事件

之前在一个场景中,遇到组件需要调用父组件中的方法tableInit(),字组件调用父组件常用的有三种方法,具体参考:https://www.cnblogs.com/jin-zhe/p/9523782.html

后来我使用的是自定义组件的方式,也算是一个小的知识点吧,在这里记录一下

首先,在需要使用的组件里面先声明这个组件:

import whitecityedit from "./components/whitecityedit";
import showdialog from "./components/showdialog";
export default {
  components: {
    whitecityedit,
    showdialog
  },

在组件中去调用:

<whitecityedit ref="whitecityedit" v-on:whitecityedit="tableInit"></whitecityedit>
 <showdialog ref="showdialog"></showdialog>

v-on:whitecityedit="tableInit",这个是自定义事件,表示要调用的哪个方法

//编辑
    btnEdit: function(id) {
      this.$refs["whitecityedit"].openDialog(id);
    },

这个是弹出组件。openDialog是对应组件中的一个方法。

 methods: {
    openDialog: function(id) {
      let that = this;
      that.dialogShow = true;
      that.formData.PWCDataFlag = 1;
      that.formData.PWCCountryName = "";
      that.formData.PWCCountryId = "";
      that.formData.PWCId = 0;
      that.formData.PWCCountryPinYin = "";
      that.changeAble = false;
      if (typeof id == "undefined") {
        return false;
      }
      that.loadData(id);
    },

然后,在组件中:

callMethod: function() {
      this.$emit("whitecityedit");//可以有第二个参数,是传的参数
    }

whitecityedit  这个对应的是  自定义事件的那个事件 的名字。

这样就可以调用自定义的事件了

原文地址:https://www.cnblogs.com/taotaozhuanyong/p/11592656.html