英文:
Vue with TypeScript: How to access component properties in type safe way
问题
Sure, here are the translated parts of your code:
我对Vue的setup API还不太了解,有一件事仍然困扰着我:我需要从父组件访问子组件的属性。它可以正常工作,但我无法正确定义TypeScript的类型。我总是收到TS错误,说属性不存在。从TypeScript的角度看,似乎是正确的,因为在我定义的对象中确实没有该属性。但一定有办法让TS理解。
<template>
<child ref="child" />
</template>
<script lang="ts">
import Child from 'child.vue';
export default {
name: 'parent',
mounted() {
const child: Child = this.$refs.child;
console.log(child.myprop); // TS2339: Property 'myprop' does not exist on type...
}
}
</script>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'child',
setup(props, context) {
const myprop = 1;
context.expose({ myprop });
return { myprop };
}
})
</script>
英文:
I am new to Vue's setup API and one thing still eludes me: I need access to properties of a child component from a parent component. It works fine, but I cant get the typescript definition right. I always get the TS error, that the propery does not exist. And from TypeScript perspective it seems to be correct, as there is no property in the object I defined. But there must be a way to make TS understand.
<template>
<child ref="child" />
</template>
<script lang="ts">
import Child from 'child.vue'
export default {
name: 'parent',
mounted() {
const child: Child = this.$refs.child;
console.log(child.myprop); // TS2339: Property 'myprop' does not exist on type...
}
}
</script>
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
name: 'child',
setup(props, context) {
const myprop = 1;
context.expose({myprop});
return {myprop};
}
})
</script
答案1
得分: 1
你在这里混合使用了组合式 API 和选项式 API。
如果将父组件重写为使用组合式 API,与类型一起工作会更容易:
import Child from 'child.vue'
export default {
name: 'parent',
setup() {
const childRef = ref<InstanceType<typeof Child>>();
onMounted(() => {
console.log(childRef.value?.myProp);
})
return { childRef };
}
}
英文:
You are mixing Composition API and Options API here.
if you rewrite the parent component to use Composition API, working with types would be easier:
import Child from 'child.vue'
export default {
name: 'parent',
setup() {
const childRef = ref<InstanceType<typeof Child>>();
onMounted(() => {
console.log(childRef.value?.myProp);
})
return { childRef };
}
}
答案2
得分: 1
尝试这个:
const child: InstanceType<typeof Child> = this.$refs.child;
或者这个:
const child = this.$refs.child as Child;
英文:
Try this:
const child: InstanceType<typeof Child> = this.$refs.child;
or this:
const child = this.$refs.child as Child;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论