vue3中子组件向父组件暴露方法并传值,同样兼容老写法
1、父组件
<template> <div class="home"> <h1>父组件</h1> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld @changeMsg="changeMsg" :msg="msg" /> <h1>{{num}}</h1> </div> </template> <script> import { reactive, toRefs } from 'vue'; import HelloWorld from '@/components/HelloWorld'; export default { setup() { const state = reactive({ msg: '点击修改父组件传值', num: 0 }); let changeMsg = x => { state.num += x; }; return { ...toRefs(state), changeMsg }; }, name: 'Home', components: { HelloWorld } }; </script> <style scoped> .home { color: red; border: 1px solid red; } </style>
2、子组件
<template> <div class="hello"> <h1>子组件</h1> <h1 class="pointer" @click="notifyParent">{{ msg }}</h1> </div> </template> <script> import { toRefs } from 'vue'; export default { setup(props, context) { console.log(context); let notifyParent = () => { context.emit('change-msg', 2); }; return { ...toRefs(props), notifyParent }; }, name: 'HelloWorld', props: { msg: String } }; </script> <style scoped> .hello { margin: 20px; color: green; border: 1px solid green; } .pointer{ cursor: pointer; } </style>
setup的第二个参数中包含了 attr emit slot
其中emit用于向父组件提交事件,需要注意的是vue3中的emit中的方法名不再支持驼峰写法,但父组件依旧支持驼峰和“-”间隔的写法,
emit其余用法和vue2相同
效果图