繁体   English   中英

使用动态 ref 名称将 ref 注入到 vue3 组件中

[英]Inject ref into vue3 component with dynamic ref name

我想要类似这样的东西来工作:

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 显示数据确实已注入,但没有任何内容呈现,就好像它仍然是空的。

<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();
    },

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM