[英]Inject ref into vue3 component with dynamic ref name
I would like something similar to this to work:我想要类似这样的东西来工作:
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
}
},
And then I try to load it dynamically, but this doesn't work:然后我尝试动态加载它,但这不起作用:
mounted() {
this.data = inject(this.step_data) as StepData;
console.log("data:" + JSON.stringify(this.data));
}
The console.log shows the data did get injected, but nothing renders as if it is still empty. 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();
},
So now this component is fully reusable, it can point to whatever step data I want to inject.所以现在这个组件是完全可重用的,它可以指向我想要注入的任何步骤数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.