自定义指令/事件
指令
https://v3.cn.vuejs.org/guide/custom-directive.html#简介
自定义focus,自定义的前面要加个v-
<input v-focus /> //让输入框聚焦
全局:
app.directive("focus", {
mounted(el) {
el.focus();
},
})
局部:
<script>
export default {
directives: {
focus: {
// 指令的定义
mounted(el) {
el.focus()
}
};
};
</script>
事件($emit),一般是用于子组件触发父组件的特定事件
- 为子组件添加一个自定义的触发事件
Father.vue
<Son @random="handler" /> //如果要接受参数,这里就不要加括号,推荐不加括号
methods: {
handler(data) { //如果有参数,在这里接收
alert('子组件触发了我')
}
}
- 由子组件来触发这个自定义的random事件
Son.vue
<button @click="touch()">触发父组件方法</button>
<script>
export default {
【1】
methods: {
touch() {
this.$emit("random") //此处两个参数 自定义事件的name: String, name事件绑定的方法的参数data: any
}
}
};
</script>
【1】可有可无,有:
- 不检验:
emits: ["random"]//把事件罗列出来 - 检验:
emits: {
random: (params) => {
//一些操作,random事件先来到这里检验(一般是检验参数是否符合规格),然后再执行绑定的事件(即Father.vue中的handler方法)
}
}
浙公网安备 33010602011771号