Parent and child components pass values
- One-way data flow pattern: It is best for children not to directly modify the value passed by the parent. If the parent passes a reference, direct modification of the value by the child may affect other children. Child components can modify the copy value by saving the copy
- Child component passes value to parent component: emit method fires event outward
The parent component passes values to its children via properties, and the children throw events
Component parameter verification and non-props feature
- Type restrictions
Vue.component.props ('child',{props:{content: [Number, String] }, template:'<div>{{content}}</div>' })Copy the code
- Custom restrictions
Vue.component('child',{
props:{
content: {
type: String | Number,
required: true,
defaule: 'default value',
validator: function(value){
return (value.length > 5)
}
}
},
template:'<div>{{content}}</div>'
})
Copy the code
- The props feature: When the parent uses a child component, the child component has a declaration in props, which can be obtained through interpolation or this.xxx
Non-props feature: The non-props feature is displayed in the DOM node if the sub-component does not declare that it needs to receive anything
Binding native Events
<child content="123121" @click="handleClick" ></child>
Copy the code
Values passed between non-parent and child components
- Using vuex
- Use publish subscribe (bus mechanism)
/** Each vue instance has a bus attribute and points to the same Vue instance. 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 (){/** the scope of this is different from that of this. $on('change', function({content}){console.log(this,_this, function({content})){console.log(this,_this, this.content, _this.content, content); _this.selfContent = content }) } }) let vm = new Vue({ el: '#root' })Copy the code