父组件为子组件传递数据(数据校验)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<child1-component
:root-name="name"
:root-age="age"
:root-gender="gender"
:root-marry="marry"
:root-wechat="wechat"
:root-hobby="hobby"></child1-component>
</div>
<script src="./vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
name: '苑文浩',
age: 20,
gender: true,
marry: '已婚',
wechat: '1271876231873',
hobby: '学习'
},
components: {
'child1-component': {
props: {
// 必须要传入,并且数据类型必须是字符串。
rootName: {
type: String,
required: true
},
// 可以不传递,但是,一旦传递,则数据类型必须是 Number 类型
rootAge: Number,
// 可以不传递,但是,一旦传递,则数据类型必须是 Boolean 或者 String 类型
rootGender: [Boolean, String],
// 可以不传递,默认是 '未婚',一旦传递,则数据类型必须是 String 类型
rootMarry: {
type: String,
default: '未婚'
},
// 可以不传递,默认是 '110',一旦传递,则数据类型必须是 String 类型
rootWechat: {
type: String,
default () {
return '110'
}
},
// 可以不传递,一旦传递,数据类型必须是字符串,并且,必须是数组中包含的值。
rootHobby: {
type: String,
// 自定义校验器,如果传入的数据合法,则返回 true,否则返回 false
validator (hobby) {
return ['吃饭','睡觉','学习'].includes(hobby)
}
}
},
data() {
return {
child1Message: 'child1组件的数据'
}
},
template: `<div>
<h2>{{child1Message}}</h2>
<h2>{{rootName}}</h2>
<h2>{{rootGender}}</h2>
<h2>{{rootMarry}}</h2>
<h2>{{rootWechat}}</h2>
<h2>{{rootHobby}}</h2>
</div>`
}
}
});
</script>
</body>
</html>
本文作者:张尊娟
本文链接:https://www.cnblogs.com/wszzj/p/16812697.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步