Communication between components vue

One,props/$emit

Parent component by propsway of transmitting data to the sub-assembly, through the $emitsub-assembly may communicate with the parent component.

1. The value passed to the parent component subassembly

propIt can only be transferred from one component to the next component (component Sons), i.e. a so-called one-way data flow. And propread-only, can not be modified, all changes will fail and a warning.

A chestnut:
subassembly article.vuehow to obtain the parent component section.vuedata Articles: [ "Dream of the Red ',' Journey to the West ',' Three Kingdoms']

//section父组件
<template>
  <div class="section">
    <com-article :articles="articleList"></com-article>
  </div>
</template>

<script>
import comArticle from './article.vue'
export default{
  name: 'HelloWorld',
  components: { comArticle }
  data(){
     return {
        articleList: ['红楼梦', '西游记','三国演义']
     }
   }
}
</script>

//article子组件
<template>
  <div>
    <span v-for="(item, index) in articles" :key="index">{{item}}</span>
  </div>
</template>

<script>
export default{
   props: ['articles']
}
</script>

2. parent component subassembly to pass values

$emitBinding a custom event, when this statement is executed, it will arg parameter passed to the parent components, the parent listens and receive parameters via v-on.
: Chestnut two
display index in the array ariticle the item, the parent component on the basis of the example, click on the page rendered in

//section父组件
<template>
  <div class="section">
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
    <p>{{ currentIndex }}</p>
  </div>
</template>

<script>
import comArticle from './article.vue'
export default{
  name: 'HelloWorld',
  components: { comArticle }
  data(){
     return {
        currentIndex: -1,
        articleList: ['红楼梦', '西游记','三国演义']
     }
   },
   methods: {
    onEmitIndex(idx) {
      this.currentIndex = idx
    }
  }
}
</script>

//article子组件
<template>
  <div>
    <span v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</span>
  </div>
</template>

<script>
export default{
   props: ['articles'],
   methods: {
    emitIndex(index) {
      this.$emit('onEmitIndex', index)
    }
  }
}
</script>

two,$children / $parent

When it is desired to directly access the parent component subassembly, the subassembly direct access to the parent component, subassembly or component to access the root. can use$children / $parent

Access parent component sub-assemblies: Use$children或$refs

  • $childrenAll sub-components can access the parent element, the return type is an array that contains all the subcomponents objects, access can be further sub-assembly properties, methods, etc.
  • $refsMay acquire a specific sub-assembly, $ refs ref and instructions are typically used together. A first sub-assembly provided to ref属性bind a particular's ID. Then this.$refs.IDyou can access to the sub-assemblies on.

Sub-components to access the parent component: use $parent, returns an object

three,provide/ inject

provide/ injectIs vue2.2.0 new api, is simply the parent component by provide来提供变量, and then by the subassembly inject来注入变量.

No matter how deeply nested sub-components, as long as the call inject, you can inject provide data in, without being limited to only get data from the current props property of the parent assembly

Chestnut:
Suppose there are three components: A.vue, B.vue, C.vue wherein component B is a child of C, B is the subassembly A

//A.vue
<template>
  <div>
    <comB></comB>
  </div>
</template>

<script>
  import comB from '../components/test/comB.vue'
  export default {
    name: "A",
    //父组件用provide定义变量
    provide: {
      for: "demo"
    },
    components:{
      comB
    }
  }
</script>

//B.vue
<template>
  <div>
    {{demo}}
    <comC></comC>
  </div>
</template>

<script>
  import comC from '../components/test/comC.vue'
  export default {
    name: "B",
    //子组件用inject注入该变量
    inject: ['for'],
    data() {
      return {
        demo: this.for
      }
    },
    components: {
      comC
    }
  }
</script>

//C.vue
<template>
  <div>
    {{demo}}
  </div>
</template>

<script>
  export default {
    name: "C",
    inject: ['for'],
    data() {
      return {
        demo: this.for
      }
    }
  }
</script>

Fourth, the event buseventBus

eventBusAlso known as event bus, you can use it as a bridge concept in vue, just as is the same for all components share events center, you can register to receive or send events to the event center, so components can notify other components. eventBus there are inconveniences, when a large project, it is easy to make it difficult to maintain a disaster

1. Initialization

Create an event bus and export it to other modules or can be used to listen to it.

import Vue from 'vue'
export const EventBus = new Vue()

2. send events and receive events

Suppose there are two components: additionNum 和 showNumto be brothers component assembly may be a parent-child; this component as an example to brother:

<template>
  <div>
    <show-num-com></show-num-com>
    <addition-num-com></addition-num-com>
  </div>
</template>

<script>
import showNumCom from './showNum.vue'
import additionNumCom from './additionNum.vue'
export default {
  components: { showNumCom, additionNumCom }
}
</script>

//addtionNum.vue 中发送事件
<template>
  <div>
    <button @click="additionHandle">+加法器</button>    
  </div>
</template>

<script>
import {EventBus} from './event-bus.js'

export default {
  data(){
    return{
      num:1
    }
  },
  methods:{
    additionHandle(){
      EventBus.$emit('addition', {
        num: this.num++
      })
    }
  }
}
</script>

//showNum.vue 中接收事件
<template>
  <div>计算和: {{count}}</div>
</template>

<script>
import { EventBus } from './event-bus.js'
export default {
  data() {
    return {
      count: 0
    }
  },
  mounted() {
    EventBus.$on('addition', param => {
      this.count = this.count + param.num;
    })
  }
}
</script>

3. Remove event listeners

import { eventBus } from 'event-bus.js'
EventBus.$off('addition', {})

Five, Vuex

1) Vuex Introduction

Vuex is a specially developed for Vue.js application state management. It uses the status of all components of the centralized storage management applications, and to ensure appropriate rules state in a predictable manner changed.
Vuex solved 多个视图依赖于同一状态and 来自不同视图的行为需要变更同一状态issues to focus developers focus on data rather than the data update on transfer between the components

2) Vuex each module

  • state: for storing data, only the data in the source store
  • getters: computing the attribute vue as secondary packaging based on state data, filter data used in the data and a plurality of correlation calculation
  • mutations: a similar manner, the only way to change the state data, and can not be used to handle asynchronous events
  • actions: similar mutation, mutation to change the state to submit, not directly change the status, can contain any asynchronous operation
  • modules: similar namespace for each module in the items defined separately and a state operation, easy to maintain

six,localStorage / sessionStorage

This communication is relatively simple, drawbacks and status data is confusing, is not easy to maintain. By window.localStorage.getItem(key)acquiring data by window.localStorage.setItem(key,value)storing data

Pay attention to JSON.parse() / JSON.stringify()make the data format conversion localStorage / sessionStoragecan be combined vuex, lasting preservation of data while using vuex solve the data state and confusion.

Seven,$attrs与 $listeners

Guess you like

Origin www.cnblogs.com/sunidol/p/11458872.html