【问题标题】:Inject ref into vue3 component with dynamic ref name使用动态 ref 名称将 ref 注入 vue3 组件
【发布时间】:2022-02-04 19:00:44
【问题描述】:

我希望类似这样的工作:

import { ref, defineComponent, inject } from "vue";
export default defineComponent({
  name: "ProgressBar",
  setup() {
    //this works with hard-coded "StepData", but this.Step_Data is not available here
    // const data = inject("StepData") as StepData;
    //but if I want to pass the name of the injected data instead I first create a blank data:
    const data = ref<StepData>({} as StepData);
    return {
      data,
    };
  },
  methods: {},
  props: {
      step_data: {
          type: String,
          required: true
      }
  },

然后我尝试动态加载它,但这不起作用:

  mounted() {
    this.data = inject(this.step_data) as StepData;
    console.log("data:" + JSON.stringify(this.data)); 
  }

console.log 显示数据确实被注入了,但没有任何东西呈现,就好像它仍然是空的一样。

【问题讨论】:

    标签: typescript vuejs3 inject


    【解决方案1】:
    <script lang="ts">
    import { defineComponent, inject, reactive, getCurrentInstance, type PropType } from "vue";
    import type { StepData } from "../types/types";
    
    export default defineComponent({
      name: "ProgressBar",
      components: {
        IconCheck,
        LocCtrl,
      },
      props: {
        isHorz: {
          type: Boolean,
          default: true,
        },
        onClick: {
          type: Function,
          default: null,
        },
        locPage: {
          type: String,
          required: true,
        },
        locKeys: {
          type: Array as PropType<string[]>,
          required: true
        },
        stepDataSource: {
          type: String,
          required: true
        }
      },
      setup() {
        const stepData = {} as StepData;
        const data = reactive ({
          stepData
        });
    
        return {
          data
        };
      },
      mounted() {
        this.getStepData();
      },
      methods: {
        async getStepData() {
          const stepData =  inject(this.stepDataSource) as StepData;
          this.data.stepData = stepData;
          const instance = getCurrentInstance();
          instance?.proxy?.$forceUpdate();
        },
    

    所以现在这个组件是完全可重用的,它可以指向我想要注入的任何步骤数据。

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2021-03-26
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 2022-08-06
      • 2020-09-08
      相关资源
      最近更新 更多