目标:掌握使用props选项和emits选项完成父子组件通讯。
- 父传子:props
- 子传父:emits
父组件
<template>
<h1>父组件</h1>
<!-- <reactive></reactive> -->
<!-- <life /> -->
<!-- <toRefVue /> -->
<!-- <toRefsVue /> -->
<!-- <refVue></refVue> -->
<!-- <composeApiDemoVue></composeApiDemoVue> -->
<!-- <computedVue /> -->
<!-- <watchVue /> -->
<parentChidChatVue :msg="msg" @change-msg="changeMsg"/>
</template>
<script>
import {ref} from 'vue'
import parentChidChatVue from './components/parentChidChat.vue'
// import computedVue from './components/computed.vue'
// import life from './components/life.vue'
// import reactive from './components/reactive.vue'
// import toRefVue from './components/toRef.vue'
// import toRefsVue from './components/toRefs.vue
// import watchVue from './components/watch.vue'
// import Ref_shuxing from './components/ref_shuxing.vue'
// import refVue from './components/ref.vue'
export default {
name: 'App',
components: {
// life
// reactive
// toRefVue
// refVue,
// computedVue
// Ref_shuxing
parentChidChatVue
},
// 1.setup是一个新的组件选项,作为组件中使用组合API的起点
// 2.从组件的生命周期来看,它的执行在组件实例创建前`vue2.x的beforeCreate`执行
// 3.这就意味着在setup函数中this还不是组件实例,此时是undefined。
// 4.在模板中需要使用的数据和函数,需要在setup返回
setup(){
// 定义数据和函数
console.log('setup',this)
let msg = ref("hi vue3.0")
const say = ()=>{
console.log('我是方法');
}
function changeMsg(val){
msg.value = val
}
return {
msg,
say,
changeMsg
}
}
}
</script>
子组件
<template>
<div class="parentChildChat">
子组件
{{msg}}
<button @click="changeMsg">修改父组件信息</button>
</div>
</template>
<script>
export default {
name:'parentChildChat',
props:{
msg:{
type:String,
default:''
}
},
//这有两参数,一个props,另外一个上下午context,里面就包含emit事件
setup(props,{emit}){
// 1.可以在模板中直接使用props中的msg
// 2.在setup中使用,需要props参数传递过来
//获取父组件数据msg
console.log(props.msg)
// 向父组件传值
function changeMsg(){
emit('change-msg','修改了的信息')
};
return {
changeMsg
}
}
}
</script>
总结
- 父传子:在setup中使用props数据
setup(props){// props就是富组件数据}
- 子传父:触发自定义事件的时候emit来着
setup(props,{emit}){ //emit 就是触发事件函数}
- 在vue3.0中 v-model和.sync 已合并成为v-model指令。