Vue3.0 父子组件通信、 父子组件传值


方式1 Props

父组件代码

<template>
  <!-- 父组件 -->
  <div class="parent">
    <Child :num="count" @handle="changeValue" />
    <button @click="add">父组件的按钮</button>
  </div>
</template>
<script lang="ts">
import Child from './components/child.vue'
import { defineComponent, reactive, toRefs } from 'vue'
export default defineComponent({
  name: '',
  props: {},
  components: { Child },
  setup () {
    const state = reactive({
      count: 1
    })

    const add = (): void => {
      state.count += 1
    }

    const changeValue = (num: number) => {
      state.count += num
    }
    return {
      ...toRefs(state),
      add,
      changeValue
    }
  }
})
</script>

 

子组件代码

<template>
  <div class="child">
    <h1> 父组件传入的值:{{ num }}</h1>
    <button @click="changeParentNum('1111')">子组件的按钮</button>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'child',
  props: {
    num: Number
  },
  setup (props, ctx) {
    const changeParentNum = () => {
      // 通过ctx调用emit事件 需要注意的是Vue2.x中使用 $emit切勿混淆
      ctx.emit('handle', 2)
    }
    return {
      changeParentNum
    }
  }
})
</script>

 

 

方式2 

provide / inject
 
父组件给予
import { defineComponent, inject } from 'vue'
 export default defineComponent({
  setup () {
    provide('msg', 'hello')
  }
})

子组件接收

<script lang="ts">
import { defineComponent, inject } from 'vue'
export default defineComponent({
  name: 'child',
  setup (props, ctx) {
    const a = inject('msg')
    return {
      a
    }
  }
})
</script>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM