一、自定义事件作用
父组件是使用 props
传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件
!
二、如何使用自定义事件
可以使用 v-on
绑定自定义事件, 每个 Vue 实例都实现了事件接口(Events interface),即:
- 使用
$on(eventName,fn)
监听事件 - 使用
$emit(eventName, data)
触发事件
<template>
<div>
<p><a @click="click()">click</a></p>
</div>
</template>
<script>
export default {
name: "CT",
props: {
id: {
type: String,
default: "CT",
},
},
data() {
return {};
},
mounted() {
console.log(this.$options.name);
},
methods: {
click() {
this.$emit("getData", "from CT data");
},
},
};
</script>
<template>
<div>
<p>BT</p>
<CT ref="ct"></CT>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: { CT },
data() {
return {};
},
mounted() {
this.$refs.ct.$on("getData", (data) => {
console.log(data);
});
},
methods: {},
};
</script>
三、$on(eventName,fn)
另一种写法
父组件可以在使用子组件的地方直接用 v-on:eventName
(@eventName
) 来监听子组件触发的事件。
<template>
<div>
<p><a @click="click()">click</a></p>
</div>
</template>
<script>
export default {
name: "CT",
props: {
id: {
type: String,
default: "CT",
},
},
data() {
return {};
},
mounted() {
console.log(this.$options.name);
},
methods: {
click() {
this.$emit("getData", "from CT data");
},
},
};
</script>
<template>
<div>
<p>BT</p>
<CT v-on:getData="getData($event)"></CT>
<CT @getData="getData2($event)"></CT>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: { CT },
data() {
return {};
},
mounted() {},
methods: {
getData(event) {
console.log("getData: ", event);
},
getData2(event) {
console.log("getData2: ", event);
},
},
};
</script>
四、自定义事件只触发一次$once(eventName,fn)
<template>
<div>
<p><a @click="click()">click</a></p>
</div>
</template>
<script>
export default {
name: "CT",
props: {
id: {
type: String,
default: "CT",
},
},
data() {
return {};
},
mounted() {
console.log(this.$options.name);
},
methods: {
click() {
this.$emit("getData", "from CT data");
},
},
};
</script>
<template>
<div>
<p>BT</p>
<CT ref="ct"></CT>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: { CT },
data() {
return {};
},
mounted() {
this.$refs.ct.$once("getData", (data) => {
console.log(data);
});
},
methods: {},
};
</script>
五、解绑$off('eventName')
<template>
<div>
<p><a @click="click()">click</a></p>
</div>
</template>
<script>
export default {
name: "CT",
props: {
id: {
type: String,
default: "CT",
},
},
data() {
return {};
},
mounted() {
console.log(this.$options.name);
},
methods: {
click() {
this.$emit("getData", "from CT data");
},
},
};
</script>
<template>
<div>
<p>BT - <span @click="offEvent()">offEvent</span></p>
<CT ref="ct"></CT>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: { CT },
data() {
return {};
},
mounted() {
this.$refs.ct.$on("getData", (data) => {
console.log(data);
});
},
methods: {
offEvent() {
this.$refs.ct.$off("getData");
},
},
};
</script>
vm.$off('eventName')
:解绑一个自定义事件vm.$off(['eventName', 'demo'])
:解绑多个自定义事件vm.$off()
:解绑所有的自定义事件