provide 和 inject 祖孙传递数据

父组件 :  

<template>
  <div>AppContent: {{ name }}</div>
  <button @click="name = 'kobe'">app btn</button>
  <show-info></show-info>
</template>

<script>
  import { provide, ref } from 'vue'
  import ShowInfo from './ShowInfo.vue'

  export default {
    components: {
      ShowInfo
    },
    setup() {
      const name = ref("why")

      provide("name", name)
      provide("age", 18)

      return {
        name
      }
    }
  }
</script>

<style scoped>
</style>
子组件 : 

<template>
  <div>ShowInfo: {{ name }}-{{ age }}-{{ height }} </div>
</template>

<script>
  import { inject } from 'vue'

  export default {
    setup() {
      const name = inject("name")
      const age = inject("age")
      const height = inject("height", 1.88)

      return {
        name,
        age,
        height
      }
    }
  }
</script>

<style scoped>
</style>

 

posted @ 2022-08-24 15:04  杨建鑫  阅读(13)  评论(0编辑  收藏  举报