Vue3 defineComponent 函数:使用 TypeScript 定义组件
在 Vue3 中,defineComponent 函数用于定义一个组件。它的用法如下:
import { defineComponent } from 'vue';
export default defineComponent({
name: 'MyComponent',
props: {
msg: String
},
setup(props) {
return {
count: 0,
increment() {
this.count++;
}
};
},
template: `
<div>
<p>{{ msg }}</p>
<button @click="increment">Count: {{ count }}</button>
</div>
`
});
其中,defineComponent 接受一个对象作为参数,这个对象包含了组件的各种配置信息:
name表示组件的名称;props表示组件的属性;setup函数用于初始化组件的数据和方法;template表示组件的模板。
在 setup 函数中,可以通过 props 参数获取组件的属性,并返回组件的数据和方法。在模板中,可以通过双花括号语法获取数据和方法。
defineComponent 函数可以和 TypeScript 配合使用,可以在组件中使用 TypeScript 类型定义。例如:
import { defineComponent } from 'vue';
interface Props {
msg: string;
}
interface Data {
count: number;
}
export default defineComponent({
name: 'MyComponent',
props: {
msg: String
},
data(): Data {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
},
template: `
<div>
<p>{{ msg }}</p>
<button @click="increment">Count: {{ count }}</button>
</div>
`
});
原文地址: https://www.cveoy.top/t/topic/oXfA 著作权归作者所有。请勿转载和采集!