Vue给组件传值限制传入的字符串的值是指定的值
可以通过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',就会报一个警告。
原文地址: https://www.cveoy.top/t/topic/bhL3 著作权归作者所有。请勿转载和采集!