vue3中在setup方法中使用 provide,inject,组件上下层,直接传值和方法


一个简简单单的案例

app.vue

<template>
  <div>
    app
    <Second/>
  </div>
</template>
<script>
import { provide } from 'vue';
import Second from './components/Second.vue'
export default {
    components:{
      Second
    },
    setup(){
        //const data = 'hello world--from app';
        const method = () => console.log('hello world!!!---from app');
        
        //provide('data',data);
        provide('method',method)
    }
}
</script>

/components/Second.vue

<template>
  <div>
    second page:{{ data }}
    <Third/>
  </div>
</template>
<script>
import { inject } from 'vue';
import Third from './Third.vue'
export default {
  name:'second',
  components:{
    Third
  },
  setup(){
    const data = inject('data','second data value');
    // app没有provide data,不是provide data的值,是直接没有provide data;
    // 这时候会给data赋值 "second data value"
    const method = inject('method');
    method();
    
    return {
      data,
      method
    }
  }
}
</script>

/components/Third.vue

<template>
    <div>
      <p>third page: {{ data }}</p>
    </div>
</template>
 
<script>
  import { inject } from 'vue';
  export default {
    name: 'third',
    components: {},
    setup(){
      const data = inject('data','third data value');
      const method = inject('method');
      method();
      return {
        data,
        method
      }
    }
  }
</script>
 
<style>
</style>
posted @ 2023-03-27 10:45  盘思动  阅读(237)  评论(0编辑  收藏  举报