Vue3:自定义事件
//父组件HomeView <template> <div> <MyBox1 @myclick="fn" @my-event="fm"></MyBox1> </div> </template> <script setup> import MyBox1 from "../components/MyBox1.vue" let fn = (arg) => { console.log(6666, arg) } let fm = (arg) => { console.log(77777, arg); } </script> //子组件MyBox1 <template> <div @mousemove="change1"> <button @click="change">点击触发myevent事件</button> </div> </template> <script > export default { methods: { change() { this.$emit('myclick', "helo666"); }, change1() { this.$emit('myEvent', "121212"); } }, } </script>
可以通过 emits
选项在组件上定义发出的事件
//父组件 <HomeView @my-event="fn" @my-submit="fn1"></HomeView> //子组件 <template> <div @mouseenter="fm"> <button @click="fn">点我触发mybtn组件内部的myclick事件</button> </div> </template> <script> export default { emits:["myEvent","myclick"], methods:{ fn(){ this.$emit("myClick",200) }, fm(){ this.$emit("click",300) } } } </script>
//父组件 <HomeView v-model:title="bookTitle"></HomeView> //子组件 //1.接收参数 props:["title"] //2.定义事件 emits: ['update:title'] //3.触发事件 this.$emit("update:title","子组件传递给父组件的值")
//2.0这样写会有矛盾 <MyVmodel v-model="msg" v-model="msg2" v-model="msg3"></MyVmodel> //2.0应该这样写: <MyVmodel v-model="msg" :msg2="msg2" @changemsg2="changemsg2" :msg3="msg3" @changemsg3="changemsg3"> </MyVmodel> js: changemsg2(arg){this.msg2=arg} changemsg3(arg){this.msg3=arg} //3.0 <MyVmodel v-model="msg" v-model:msg2="msg2" v-model:msg3="msg3"></MyVmodel> //父组件 <user-name v-model:msg1="msg1" v-model:msg2="msg2" ></user-name> //子组件 //1.接收参数 props:["msg1","msg2"] //2.定义事件 emits: ['update:msg1','update:msg2'] //3.触发事件 this.$emit('update:msg1',"子组件传递给父组件的值1") this.$emit('update:msg2',"子组件传递给父组件的值2")