Vue 组件传值限制字符串类型 - 使用 props validator
可以通过 props 中的 validator 属性来限制传入的字符串的值是指定的值。
示例代码:
<template>
<div>
<child-component :message='message'></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
message: 'hello',
};
},
};
</script>
在 ChildComponent 中,可以通过 props 限制传入的 message 只能是指定的值:
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
validator(value) {
return ['hello', 'world'].indexOf(value) !== -1;
},
default: 'hello',
},
},
};
</script>
这样,如果在父组件中传入的 message 不是'hello' 或'world',就会报一个警告。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mJA6 著作权归作者所有。请勿转载和采集!