总结为三大类:vue
props
/ $emit
$children
/ $parent
provide
/ inject
ref
/ refs
localStorage
/ sessionStorage
$attrs
与 $listeners
props
; $parent
/ $children
; provide
/ inject
; ref
; $attrs
/ $listeners
eventBus
; vuexeventBus
;Vuex;provide
/ inject
、$attrs
/ $listeners
props
/ $emit
article.vue
中如何获取父组件section.vue
中的数据articles:['红楼梦', '西游记','三国演义']
// section父组件
<template>
<div class="section">
<com-article :articles="articleList"></com-article>
</div>
</template>
<script>
import comArticle from './test/article.vue' export default { name: 'HelloWorld', components: { comArticle }, data() { return { articleList: ['红楼梦', '西游记', '三国演义'] } } } </script>
// 子组件 article.vue
<template>
<div>
<span v-for="(item, index) in articles" :key="index">{{item}}</span>
</div>
</template>
<script>
export default { props: ['articles'] } </script>
总结: prop 只能够从上一级组件传递到下一级组件(父子组件),即所谓的单向数据流。并且 prop 只读,不可被修改,全部修改都会失效并警告。程序员
$emit
我本身的理解是这样的:
$emit
绑定一个自定义事件, 当这个语句被执行时, 就会将参数arg传递给父组件,父组件经过v-on监听并接收参数。 经过一个例子,说明子组件如何向父组件传递数据。 在上个例子的基础上, 点击页面渲染出来的
ariticle
的
item
, 父组件中显示在数组中的下标
// 父组件中
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{{currentIndex}}</p>
</div>
</template>
<script>
import comArticle from './test/article.vue' export default { name: 'HelloWorld', components: { comArticle }, data() { return { currentIndex: -1, articleList: ['红楼梦', '西游记', '三国演义'] } }, methods: { onEmitIndex(idx) { this.currentIndex = idx } } } </script>
<template>
<div>
<div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
</div>
</template>
<script>
export default { props: ['articles'], methods: { emitIndex(index) { this.$emit('onEmitIndex', index) } } } </script>
$children
/ $parent
$parent
和$children
就能够访问组件的实例,拿到实例表明什么?表明能够访问此组件的全部方法和data
。接下来就是怎么实现拿到指定组件的实例。
// 父组件中
<template>
<div class="hello_world">
<div>{{msg}}</div>
<com-a></com-a>
<button @click="changeA">点击改变子组件值</button>
</div>
</template>
<script>
import ComA from './test/comA.vue' export default { name: 'HelloWorld', components: { ComA }, data() { return { msg: 'Welcome' } }, methods: { changeA() { // 获取到子组件A this.$children[0].messageA = 'this is new value' } } } </script>
// 子组件中
<template>
<div class="com_a">
<span>{{messageA}}</span>
<p>获取父组件的值为: {{parentVal}}</p>
</div>
</template>
<script>
export default { data() { return { messageA: 'this is old' } }, computed:{ parentVal(){ return this.$parent.msg; } } } </script>
#app
上拿
$parent
获得的是
new Vue()
的实例,在这实例上再拿
$parent
获得的是
undefined
,而在最底层的子组件拿
$children
是个空数组。也要注意获得
$parent
和
$children
的值不同,
$children
的值是数组,而
$parent
是个对象
provide
/ inject
provide
/ inject
是vue2.2.0
新增的api, 简单来讲就是父组件中经过provide
来提供变量, 而后再子组件中经过inject
来注入变量。inject
那么就能够注入provide
中的数据,而不局限于只能从当前父组件的props属性中回去数据// A.vue
<template>
<div>
<comB></comB>
</div>
</template>
<script>
import comB from '../components/test/comB.vue' export default { name: "A", 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: ['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>
ref
/ refs
ref
:若是在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;若是用在子组件上,引用就指向组件实例,能够经过实例直接调用组件的方法或访问数据, 咱们看一个ref
来访问组件的例子:
// 子组件 A.vue
export default { data () { return { name: 'Vue.js' } }, methods: { sayHello () { console.log('hello') } } }
// 父组件 app.vue
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default { mounted () { const comA = this.$refs.comA; console.log(comA.name); // Vue.js comA.sayHello(); // hello } } </script>
eventBus
又称为事件总线,在vue中可使用它来做为沟通桥梁的概念, 就像是全部组件共用相同的事件中心,能够向该中心注册发送事件或接收事件, 因此组件均可以通知其余组件。eventBus
来实现组件之间的数据通讯呢?具体经过下面几个步骤// event-bus.js
import Vue from 'vue' export const EventBus = new Vue()
<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' console.log(EventBus) 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>
这样就实现了在组件addtionNum.vue
中点击相加按钮, 在showNum.vue
中利用传递来的 num
展现求和的结果.vuex
import { eventBus } from 'event-bus.js'
EventBus.$off('addition', {})
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. Vuex 解决了多个视图依赖于同一状态
和来自不一样视图的行为须要变动同一状态
的问题,将开发者的精力聚焦于数据的更新而不是数据在组件之间的传递上api
state
:用于数据的存储,是store中的惟一数据源getters
:如vue中的计算属性同样,基于state数据的二次包装,经常使用于数据的筛选和多个数据的相关性计算mutations
:相似函数,改变state数据的惟一途径,且不能用于处理异步事件actions
:相似于mutation
,用于提交mutation
来改变状态,而不直接变动状态,能够包含任意异步操做modules
:相似于命名空间,用于项目中将各个模块的状态分开定义和操做,便于维护// 父组件
<template>
<div id="app">
<ChildA/>
<ChildB/>
</div>
</template>
<script>
import ChildA from './components/ChildA' // 导入A组件
import ChildB from './components/ChildB' // 导入B组件
export default { name: 'App', components: {ChildA, ChildB} // 注册A、B组件 } </script>
// 子组件childA
<template>
<div id="childA">
<h1>我是A组件</h1>
<button @click="transform">点我让B组件接收到数据</button>
<p>由于你点了B,因此个人信息发生了变化:{{BMessage}}</p>
</div>
</template>
<script>
export default { data() { return { AMessage: 'Hello,B组件,我是A组件' } }, computed: { BMessage() { // 这里存储从store里获取的B组件的数据 return this.$store.state.BMsg } }, methods: { transform() { // 触发receiveAMsg,将A组件的数据存放到store里去 this.$store.commit('receiveAMsg', { AMsg: this.AMessage }) } } } </script>
// 子组件 childB
<template>
<div id="childB">
<h1>我是B组件</h1>
<button @click="transform">点我让A组件接收到数据</button>
<p>由于你点了A,因此个人信息发生了变化:{{AMessage}}</p>
</div>
</template>
<script>
export default { data() { return { BMessage: 'Hello,A组件,我是B组件' } }, computed: { AMessage() { // 这里存储从store里获取的A组件的数据 return this.$store.state.AMsg } }, methods: { transform() { // 触发receiveBMsg,将B组件的数据存放到store里去 this.$store.commit('receiveBMsg', { BMsg: this.BMessage }) } } } </script>
vuex的store.js数组
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) const state = { // 初始化A和B组件的数据,等待获取 AMsg: '', BMsg: '' } const mutations = { receiveAMsg(state, payload) { // 将A组件的数据存放于state state.AMsg = payload.AMsg }, receiveBMsg(state, payload) { // 将B组件的数据存放于state state.BMsg = payload.BMsg } } export default new Vuex.Store({ state, mutations })
let defaultCity = "上海"
try { // 用户关闭了本地存储功能,此时在外层加个try...catch
if (!defaultCity){
defaultCity = JSON.parse(window.localStorage.getItem('defaultCity')) } }catch(e){} export default new Vuex.Store({ state: { city: defaultCity }, mutations: { changeCity(state, city) { state.city = city try { window.localStorage.setItem('defaultCity', JSON.stringify(state.city)); // 数据改变的时候把数据拷贝一份保存到localStorage里面 } catch (e) {} } } })
这里须要注意的是:因为vuex里,咱们保存的状态,都是数组,而localStorage只支持字符串,因此须要用JSON转换:session
JSON.stringify(state.subscribeList); // array -> string JSON.parse(window.localStorage.getItem("subscribeList")); // string -> array
localStorage
/ sessionStorage
window.localStorage.getItem(key)
获取数据 经过window.localStorage.setItem(key,value)
存储数据JSON.parse()
/ JSON.stringify()
作数据格式转换 localStorage
/ sessionStorage
能够结合vuex
, 实现数据的持久保存,同时使用vuex解决数据和状态混乱问题.$attrs
与 $listeners
如今咱们来讨论一种状况, 咱们一开始给出的组件关系图中A组件与D组件是隔代关系, 那它们以前进行通讯有哪些方式呢?app
props
绑定来进行一级一级的信息传递, 若是D组件中状态改变须要传递数据给A, 使用事件系统一级级往上传递eventBus
,这种状况下仍是比较适合使用, 可是碰到多人合做开发时, 代码维护性较低, 可读性也低在vue2.4
中,为了解决该需求,引入了$attrs
和$listeners
, 新增了inheritAttrs
选项。 在版本2.4之前,默认状况下,父做用域中不做为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外),将会“回退”且做为普通的HTML特性应用在子组件的根元素上。异步
$attrs
:包含了父做用域中不被 prop 所识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含全部父做用域的绑定 (class 和 style 除外),而且能够经过 v-bind="$attrs" 传入内部组件。一般配合 inheritAttrs 选项一块儿使用。
$listeners
:包含了父做用域中的 (不含 .native 修饰器的) v-on 事件监听器。它能够经过 v-on="$listeners" 传入内部组件
接下来看一个跨级通讯的例子:ide
// app.vue
// index.vue
<template>
<div>
<child-com1
:name="name" :age="age" :gender="gender" :height="height" title="程序员成长指北" ></child-com1> </div> </template> <script> const childCom1 = () => import("./childCom1.vue"); export default { components: { childCom1 }, data() { return { name: "zhang", age: "18", gender: "女", height: "158" }; } }; </script>
// childCom1.vue
<template class="border">
<div>
<p>name: {{ name}}</p>
<p>childCom1的$attrs: {{ $attrs }}</p>
<child-com2 v-bind="$attrs"></child-com2>
</div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue"); export default { components: { childCom2 }, inheritAttrs: false, // 能够关闭自动挂载到组件根元素上的没有在props声明的属性 props: { name: String // name做为props属性绑定 }, created() { console.log(this.$attrs); // { "age": "18", "gender": "女", "height": "158", "title": "程序员成长" } } }; </script>
// childCom2.vue
<template>
<div class="border">
<p>age: {{ age}}</p>
<p>childCom2: {{ $attrs }}</p>
</div>
</template>
<script>
export default { inheritAttrs: false, props: { age: String }, created() { console.log(this.$attrs); // { "gender": "女", "height": "158", "title": "程序员成长" } } }; </script>
父组件经过v-model传递值给子组件时,会自动传递一个value的prop属性,函数
子组件中经过this.$emit(‘input',val)自动修改v-model绑定的值,下面看个例子。
父组件:
<template>
<div>
<child v-model="total"></child>
<button @click="increse">增长5</button>
</div>
</template>
<script>
import Child from "./child.vue" export default { components: { Child }, data: function () { return { total: 0 }; }, methods: { increse: function () { this.total += 5; } } } </script>
子组件:
<template>
<div>
<span>{{value}}</span>
<button @click="reduce">减小5</button>
</div>
</template>
<script>
export default { props: { value: Number // 注意这里是value }, methods: { reduce: function(){ this.$emit("input", this.value - 5) // 事件为input } } } </script>