Vue子组件监听父组件的事件

正常情况下,父组件可以监听子组件传递过来的事件,那么子组件怎么监听父组件的事件呢?

实际案例:
假设子组件是一个弹框表单,子组件里边我预留了一个按钮位置,用于【添加数据】或者【编辑数据】按钮,点击按钮,子组件显示弹框。

示例一:整个组件监听事件

<template>
  <div @click="changeVisiable">
    <slot></slot>
    <div v-show="visiable">显示隐藏的内容</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      visiable: false,
    };
  },

  methods: {
    changeVisiable() {
      this.visiable = !this.visiable;
    },
  },
};
</script>

父组件

<template>
  <div id="app">
    <Child>
      <button>打开</button>
    </Child>
  </div>
</template>

<script>
import Child from "./Child.vue";

export default {
  name: "app",

  data() {
    return {};
  },

  components: { Child },
};
</script>

此时也可以实现父组件中点击按钮,子组件触发相应的事件,此时,整个div标签都会接受到点击事件,范围扩大了
在这里插入图片描述

示例二:使用插槽事件

子组件

<template>
  <div>
    <slot></slot>
    <div v-show="visiable">显示隐藏的内容</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      visiable: false,
      reference: null,
    };
  },

  methods: {
    changeVisiable() {
      this.visiable = !this.visiable;
    },
  },

  mounted() {
    if (this.$slots.default) {
      this.reference = this.$slots.default[0].elm;
    }
    if (this.reference) {
      this.reference.addEventListener("click", this.changeVisiable, false);
    }
  },

  beforeDestroy() {
    if (this.reference) {
      this.reference.removeEventListener("click", this.changeVisiable, false);
    }
  },
};
</script>

父组件

<template>
  <div id="app">
    <Child>
      <button>打开</button>
    </Child>
  </div>
</template>

<script>
import Child from "./Child.vue";

export default {
  name: "app",

  data() {
    return {};
  },

  components: { Child },
};
</script>

当父组件中的按钮被点击,子组件的隐藏内容将会被显示

此方法发现这个组件写的代码量变大了

方式三:监听参数变化

<template>
  <div>
    <slot></slot>
    <div v-show="visiable">显示隐藏的内容</div>
  </div>
</template>

<script>
export default {
  props: {
    visiable: {
      type: Boolean,
      default: false,
    },
  },
};
</script>

父组件

<template>
  <div id="app">
    <Child :visiable="visiable">
      <button @click="handleClick">打开</button>
    </Child>
  </div>
</template>

<script>
import Child from "./Child.vue";

export default {
  name: "app",

  data() {
    return {
      visiable: false,
    };
  },

  components: { Child },

  methods: {
    handleClick() {
      this.visiable = !this.visiable;
    },
  },
};
</script>

此例通过父组件传递的参数控制子组件的内容显示,通过参数来实现组件通信,如果<slot> 标签的内容变化可预期,可以使用一个参数来控制是添加,还是编辑,来显示不一样的按钮形式。

参考
[ Vue ] 给 slot 插槽绑定事件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值