簡體   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