父组件App.vue
<template>
<div>
<!-- 注意点:加上冒号是动态绑定,不加上的冒号传过去的只是字符串 -->
<Navbar :my-title="title" left="返回" right="首页" :leftshow="true" :rightshow="true></Navbar>
</div>
</template>
<script>
import Navbar from './Navbar.vue'
export default {
data() {
return {
title: '首页状态',
}
},
methods: {
},
components: {
Navbar,
}
}
</script>
<style lang="scss" scoped></style>
子组件Navbar.vue
<template>
<div>
<button v-show="leftshow">{{ left }}</button>
navbar--{{ myTitle }}
<button v-show="rightshow">{{ right }}</button>
</div>
</template>
<script>
export default {
// 属性验证
props: {
myTitle: String,
// 传过来的类型可以是字符串,也可以是数字类型
left: [String, Number],
right:String,
leftshow: Boolean,
rightshow: Boolean,
}
}
}
</script>
<style lang="scss" scoped></style>
更加细致的属性验证-传法
<template>
<div>
<!-- 注意点:加上冒号是动态绑定,不加上的冒号传过去的只是字符串 -->
<Navbar :my-title="title" left="返回" right="success" :leftshow="true"></Navbar>
</div>
</template>
<script>
import Navbar from './Navbar.vue'
export default {
data() {
return {
title: '首页状态',
}
},
methods: {
},
components: {
Navbar,
}
}
</script>
<style lang="scss" scoped></style>
<template>
<div>
<!-- 点击父组件按钮,页面改变 即父改变 子也改变 -->
<button v-show="leftshow">{{ left }}</button>
navbar--{{ myTitle }}
<button v-show="rightshow">{{ right }}</button>
</div>
</template>
<script>
export default {
// 接收
// props:['myTitle','left','right','leftshow','rightshow'],
// 属性验证
props: {
myTitle: String,
//数组写法 传过来的类型可以是字符串,也可以是数字类型
left: [String, Number],
//对象写法
leftshow: {
required: true,
type: Boolean,
},
rightshow: {
type: Boolean,
// 默认值 就算父组件没有传过来,一样可以在页面中显示
default: true
},
right: {
//必须传
required: true,
// 校验器 传过来的必须是数组中的某一个值
validator(value) {
return ['success', 'warning', 'danger'].includes(value)
}
}
}
}
</script>
<style lang="scss" scoped></style>
运行截图: