一、父组件向子组件通信
使用props属性传参(父组件的数据通过参数接口传递给子组件)
1.静态传参(参数不变)
Vue.component('my-component', {
// 像function一样,声明组件的参数名称;
props: ['message'],
// 传进来以后,你可以在组件下的模板中使用这个数据
template: '<span>{{ message }}</span>'
})
var vm = new Vue({
el: '#example'
})
<div id="example">
<my-component message='Hello World'></my-component>//传了一个固定的hello world
</div>
2.动态传参(参数动态)
<div id='example'>
<input v-model="parentMsg">
<br>
<child v-bind:my-message="parentMsg"></child>//HTML(不能使用驼峰命名)中用短横线命名,会自动转换成myMessage
</div>
Vue.component('child', {
props: ['myMessage'],
template: '<span>{{ myMessage }}</span>'
})
new Vue({
el:'#example',
data:{
parentMsg:''
}
})
v-bind:my-message=“parentMsg 就这样把一个动态响应式的参数传递给了子组件。
3.参数验证
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
}
}
}
})
二、子组件向父组件通信
Vue有两个方法是用来处理事件的:
- 侦听事件使用 $on(eventName)
- 定义和触发事件使用$emit(eventName)
使用v-on事件进行侦听,(v-on:input=''do'')他侦听到组件内部事件后,
$emit('input'),input这个事件将会传到组件外部乃至上级,从而执行父级实例的do()方法。