Parent and child components pass values

  1. 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
  2. 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

  1. Type restrictions
Vue.component.props ('child',{props:{content: [Number, String] }, template:'<div>{{content}}</div>' })Copy the code
  1. 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
  1. 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

  1. Using vuex
  2. 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