您的位置 首页 golang

vue3在setup中使用依赖注入

父组件代码

 <template>
  <div>
    <HelloWorld ref="HelloWorld" />
    <p>{{v}}---v</p>
    <p>{{objV.keyN}}---keyN</p>
  </div>
</template>

< script >
  import HelloWorld from './components/HelloWorld.vue';
  import { provide,reactive, ref,readonly } from 'vue';
  
  export default {
    name: 'App',
    setup() {
      // 使用ref、reactive为要注入的数据添加响应性
      const v = ref(1);
      const objV = reactive({
        keyN: 2
      })
      
      // 为子组件暴露修改注入数据的方法
      const changeP = () => {
        v.value++;
        objV.keyN++;
      }
      
      // 使用provide注入数据,使用 readonly 避免子组件随意更改注入的数据
      provide('name',readonly(v));
      provide('nameObj',readonly(objV));
      provide('changeP',changeP);
      
      return {
        v,
        objV
      }
    },
    data() {
      return {
      }
    },
    computed: {
    },
    watch: {
    },
    components: {
      HelloWorld,
    },
    methods: {
    }
  }
</script>

<style scoped>
  body {
     margin : 0px;
     padding : 0px;
  }
</style>  

子组件代码

 <template>
  <div>
    <div class="aC" @click="changeF"></div>
    <p>{{name}}</p>
    <p>{{nameObj.keyN}}</p>
  </div>
</template>

<script>
  import { inject } from 'vue';
  
  export default {
    props: {
    },
    data() {
      return {
      }
    },
    setup(props,context) {
      // 使用inject获取注入的数据,inject的第二个参数为添加默认值
      const name = inject('name', 'defaultValue');
      const nameObj = inject('nameObj', {});
      const changeP = inject('changeP');
      
      return {
        name,
        nameObj,
        changeP
      }
    },
    methods: {
      changeF() {
        this.changeP();
      }
    }
  }
</script>

<style scoped>
  .aC {
    width: 100px;
    height: 100px;
    background: red;
  }
</style>  

效果如下

文章来源:智云一二三科技

文章标题:vue3在setup中使用依赖注入

文章地址:https://www.zhihuclub.com/92295.shtml

关于作者: 智云科技

热门文章

网站地图