我的Vue组件中有一个道具,我不知道它的确切类型(它可以是Number或String类型),但是在同一组件上还有其他道具,它们具有定义的类型,我不想删除它们的类型定义。道具是否有接受多种不同类型(或any类型)的方法?
这是我的代码:
props: {
name: {
type: String,
default: "",
},
inputType: {
type: String,
default: "text",
},
value: {
type: Any,
required: true,
}
}我知道我可以像props: ['name', 'inputType', 'value']一样声明道具,而不必为它们定义类型,但是我想知道是否有一种方法可以定义“name”和“inputType”的类型,但是让'value‘接受任何类型呢?
我用的是Nuxt v2.15.7
相关链接:
发布于 2022-10-05 08:49:36
结果表明,我们可以使用以下语法为一个支柱定义多个类型;因此,我没有使用任何类型,而是通过定义支柱可以具有的所有类型来解决这个问题:
props: {
name: {
type: String,
default: "",
},
inputType: {
type: String,
default: "text",
},
value: {
type: [String, Number],
required: true,
}
}发布于 2021-12-26 08:08:24
尝试给它一个undefined值,如下面的示例所述:
// ignore the following two lines, they just disable warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('my-component', {
template:`<div>{{name}},{{value}}</div>`,
props:{
name:String,
value:undefined
}
})
new Vue({
el: '#app',
data() {
return {}
}
})<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<my-component name="test" value="testtt" />
</div>
https://stackoverflow.com/questions/70484942
复制相似问题