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