父子组件传值
- 单向数据流模式:子组件最好不要直接修改父组件传递过来的值 如果父组件传递过来的是一个引用,子组件直接修改值可能影响其他子组件。 子组件可以通过保存副本的方式修改副本值
- 子组件给父组件传值:emit方法向外触发事件
父组件通过属性给子组件传值,子组件抛出事件
组件参数校验与非props特性
- 类型限制
/** 定义子组件,参数校验,props中对象的键就是传递的属性名字 */
Vue.component('child',{
props:{
content: [Number, String]
},
template:'<div>{{content}}</div>'
})
- 自定义限制
Vue.component('child',{
props:{
content: {
type: String | Number,
required: true,
defaule: 'default value',
validator: function(value){
return (value.length > 5)
}
}
},
template:'<div>{{content}}</div>'
})
- props特性:父组件使用子组件时,子组件在props中有相应的声明,子组件中可通过插值表达式或者this.xxx获得
非props特性: 子组件未声明需要接收的内容 非props特性会显示在dom节点中
绑定原生事件
<child content="123121" @click="handleClick" ></child>
非父子组件之间的传值
- 使用vuex
- 使用发布订阅模式(总线机制)
/** 每个vue实例上都有bus属性 并且指向同一个vue实例,此处点击时两个组件都会触发 */
Vue.prototype.bus = new Vue()
Vue.component('child',{
data:function(){
return {
selfContent: this.content
}
},
props: {
content: String
},
template: '<div @click="handleClick" >{{selfContent}}</div>',
methods: {
handleClick: function(){
this.bus.$emit('change', { content: this.content })
}
},
mounted: function(){
/** 外面this和function中this的作用域不同,function中的this作用域不再是child组件 */
var _this = this
this.bus.$on('change', function({content}){
console.log(this,_this, this.content, _this.content, content);
_this.selfContent = content
})
}
})
let vm = new Vue({
el: '#root'
})