Vue自定义事件 事件解绑与销毁

组件自定义事件 事件解绑 组件销毁

组件标签上绑定事件,相当于给vc绑定自定义事件,此时用$emit触发.
组件内元素上绑定事件,事件的回调可以写在methods里面

子传父

  • v-on|once + $emit
  • mounted + ref + $emit

案例

App.vue

<template>
  <div id="app">
    <CustomChild @CustomEvent="getCustom" />
    <CustomChild ref="child" />
  </div>
</template>

<script>
import CustomChild from "./components/CustomChild.vue";
export default {
  name: "App",
  components: {
    CustomChild,
  },
  methods: {
    getCustom(payload) {
      console.log("getCustom: ", payload);
    },
  },
  mounted() {
    const _this = this.$refs.child;
    this.$refs.child.$on("CustomEvent2", function (payload) {
      console.log("getCustom2: ", payload);
      console.log(this === _this); // true  一般情况下this指向事件绑定的组件实例,而不是当前组件实例。 可以使用箭头函数
    });
  },
};
</script>

CustomChild.vue

<template>
  <button @click="emitSup">子传父</button>
</template>

<script>
export default {
  data: () => ({
    payload:{
      msg:'data from child'
    }
  }),
  methods:{
    emitSup(){
      this.$emit('CustomEvent',this.payload)
      this.$emit('CustomEvent2',this.payload)
    }
  }
};
</script>

<style>
h1 {
  color: salmon;
}
</style>

组件销毁与自定义事件解绑


解绑事件

this.$off('e')
this.$off(['e','e1'])
this.$off() // 所有自定义事件

销毁组件实例

this.$destory 组件销毁后,自定义事件全部失效
posted @ 2022-02-11 20:42  IslandZzzz  阅读(1501)  评论(0编辑  收藏  举报