componentization

Component systems are another important concept for Vue because it is an abstraction that allows us to build large applications from small, independent, and often reusable components. If you think about it, almost any type of application interface can be abstracted as a component tree:As follows, register the component in Vue and use:

// html
<div id="app-7">
  <ol>
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>
// js
Vue.component('todo-item', {
  props: ['todo'].template: '<li>{{ todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7'.data: {
    groceryList: [{id: 0.text: 'vegetables' },
      { id: 1.text: "Cheese" },
      { id: 2.text: 'Whatever other people eat.'}]}})Copy the code

Components by value

Parent component => Child component

1. The props attribute:

// child
props: {msg:String}
// parent
<Son  msg='hello,son'>
Copy the code

2. $attrs features

{{$attrs. MSG}} // parent <Son MSG ='hello, Son '>Copy the code

3. Refs scenario: Used to open a subcomponent popup and transfer values

< sonRef = sonRef'> mounted(){this.$refs.sonref. MSG ="hello, Son "}Copy the code

4.$children subcomponent array

// parent mounted(){this.$child [0]. MSG ="hello, son"}Copy the code

Child component => Parent component

The child component sends the definition event $emit(). When the child component listens to the event, it can get the parameter value in the parent component

// child
this.$emit('add',msg);
// parent
<Son @add="handleAdd"/>
Copy the code

Brother components

$parent- Sends defined events through the parent, which the parent receives

// brother1
this.$parent.$emit('sayHi','hi');
// brother2
this.$parent.$on('sayHi',handle)
Copy the code

Ancestors => descendants

Props layer by layer is not elegant, so use this API pair: provide/inject

// ancestor
provide(){
  return {foo:"777"}
}
// descendent
inject:['foo']
Copy the code

Any two components:

1. Event bus

// main.js
Vue.prototype.$bus=new Vue();
// child1
this.$bus.$on('foo',handle);
// child2
this.$bus.$emit('foo',msg);
Copy the code

Vuex — The ultimate solution

Slot Slot and scope slot

A portion of content can be written in a parent component file and then organized and displayed by the children, using slot slots.

<HelloWorld> <template>slot</template> <template V-slot :content> Content </template> // <div class="hello"> <slot></slot> </slot> <slot name="content"></slot> </div>Copy the code