组合API-父子通讯

目标:掌握使用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指令。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文简介 点赞 + 关注 + 收藏 = 学会了 本文讲解 Vue 3.2 组件多种通讯方式的基础用法,并且使用了 ...
    德育处主任阅读 1,278评论 0 3
  • 本文简介 点赞 + 关注 + 收藏 = 学会了 本文讲解 Vue 3.2 组件多种通讯方式的基础用法,并且使用了 ...
    德育处主任阅读 1,446评论 0 17
  • 组合API-computed函数 定义计算属性: computed函数,是用来定义计算属性的,计算属性不能修改。基...
    东邪_黄药师阅读 1,258评论 0 7
  • 在Vue3中进行父子的通讯,原理和Vue2做法差不多 1.父组件向子组件传递数据:自定义属性props 2.子组件...
    沃德麻鸭阅读 2,020评论 0 0
  • 在Vue3中进行父子的通讯,原理和Vue2做法差不多 1.父组件向子组件传递数据:自定义属性props 2.子组件...
    world_7735阅读 1,849评论 0 12