更多关于Vue.js的系列文章请点击:Vue.js开发实践(0)-目录页
prop 是父组件用来传递数据的一个自定义属性。
父组件的数据需要通过 props 把数据传给子组件,子组件需要显式地用 props 选项声明 “prop”:
<div id="app">
<child message="hello!">child>
div>
<script>
// 注册
Vue.component('child', {
// 声明 props
props: ['message'],
// 同样也可以在 vm 实例中像 "this.message" 这样使用
template: '{{ message }}'
})
// 创建根实例
new Vue({
el: '#app'
})
script>
组件间可以通过v-bind指令进行动态的数据交互:
<div id="app">
<div>
<input v-model="parentMsg">
<br>
<child v-bind:message="parentMsg">child>
div>
div>
<script>
// 注册
Vue.component('child', {
// 声明 props
props: ['message'],
// 同样也可以在 vm 实例中像 "this.message" 这样使用
template: '{{ message }}'
})
// 创建根实例
new Vue({
el: '#app',
data: {
parentMsg: '父组件内容'
}
})
script>
父组件可以通过prop属性和子组件通信,但是子组件不能使用prop属性和父组件通信,所以我们需要通过自定义事件去让子组件和父组件通信。
<div id="vue5">
<h1>子组件向父组件通信h1>
<Child v-on:sign="fatherRecevice($event)">Child>
div>
var Child = {
//子组件模板中有一个点击触发事件,以此来将消息发送给父组件
template: '<button v-on:click="sendMessageToFather">发送数据给父组件{{message}}button>',
data(){
return{
message: 'ABC'
}
},
methods: {
sendMessageToFather(){
//调用this.$emit方法唤醒v-on:sign标识的父组件方法fatherRecevice($event),第二个参数为传递的数据
this.$emit('sign',this.message);
}
}
}
new Vue({
el: '#vue5',
components: {
Child
},
methods: {
//这是父组件方法,用于接受数据
fatherRecevice(message){
alert("接受到数据"+message);
}
}
})
vue为prop参数提供了一套校验的基本数据类型:
Vue.component('example', {
props: {
// 基础类型检测 (`null` 意思是任何类型都可以)
propA: Number,
// 多种类型
propB: [String, Number],
// 必传且是字符串
propC: {
type: String,
required: true
},
// 数字,有默认值
propD: {
type: Number,
default: 100
},
// 数组/对象的默认值应当由一个工厂函数返回
propE: {
type: Object,
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
propF: {
validator: function (value) {
return value > 10
}
}
}
})