码迷,mamicode.com
首页 > 其他好文 > 详细

vue系列——组件数据通讯(二)

时间:2017-03-24 13:39:45      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:基础   render   项目   stat   更新   命名   str   lan   常量   

VUEX: https://vuex.vuejs.org,官方文档先仔细看一遍,否则基础的东西不知道看下面的内容会吃力

关于vuex的使用场景,先抄官网一段话:

虽然 Vuex 可以帮助我们管理共享状态,但也附带了更多的概念和框架。这需要对短期和长期效益进行权衡。

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 global event bus 就足够您所需了。但是,如果您需要构建是一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。

所以,简言之

项目简单就不用,利用 组件数据通讯(一)中讲到的知识点足够

如果你觉得有必要做一些全局状态管理,那就增加一个vuex.js文件

如果项目比较复杂,涉及到需要管理的全局状态模块较多,还需要引入vuex模块化,

 (一)基础实现

1. 首先写一份最简单的store单页模块

import Vue from ‘vue‘
import Vuex from ‘vuex‘
Vue.use(Vuex)

const user = {
    state: {
        name: ‘lilei‘
    },
    getters: {
        getName(state) {return state.name;}
    },
    mutations: {
        setName(state, name) {state.name = name;}
    },
    actions: {
        setName({ commit }, name) {commit(‘setName‘, name);}
    }
};

const store = new Vuex.Store(user)
export default store

  state:状态对象,很类似全局变量,但它的状态存储是响应式的(驱动页面自动更新)

  getters:对state处理后返回,相当于加工一层,在本例中其实没有做处理原样返回

  mutations:这个对象的方法负责修改state

    actions:异步操作都通过这个对象方法,它自己是不能修改state的,而是通过调用mutation

2. 在根元素中引入store

import store from ‘./vuex‘

new Vue({
  el: ‘#app‘,
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 store, render: h => h(App) })

  Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中,简单说,我们在所有子组件都可以访问到store相关对象

3.子组件读取和操作store

  3.1 通过this.$store调用

computed:{
    count () {
      return this.$store.state.count
    },
    countFromGetter () {
      return this.$store.getters.count
    }
},
methods:{    
    commit(){
      this.$store.commit(‘increment‘)
    },
    dispatch(){
      this.$store.dispatch(‘increment‘,str)
    }
}

  3.2通过vuex提供的mapState,mapGetters,mapMutations,mapActions调用

import {mapState,mapGetters,mapMutations,mapActions} from ‘vuex‘

export default {  
  computed:{
    ...mapState([‘name‘]),
    ...mapGetters([‘getName‘])
 

}, methods:{ ...mapActions([‘setName‘]), parentListener(){} } }

  这里直接使用对象扩展符去调用,注意.babelrc文件中要加入"stage-2",不然不支持该特性

1. 读取state两种方式,直接读取和通过getters,getters相当于一个中间处理器

2. 操作state两种方式,mutations和actions,在子组件中两种方式都可以使用,比如如果简单的操作直接用mutations,涉及到异步或者复杂业务可以封装公用代码到actions里面;

另外:

mutations 有一个固有参数 state,接收的是 Vuex 中的 state 对象

action 也有一个固有参数 context,但是 context 是 state 的父级,包含  state、getters

  如果希望取别名调用:

computed:mapState({
    count: state => state.count,

    // 传字符串参数 ‘count‘ 等同于 `state => state.count`
    countAlias: ‘count‘,

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
},

  

 (二)模块化store

业务复杂的情况下,我们要做一个store的模块化,否则所有的状态全堆在一个sotre中,可想而知会怎样。。

下面介绍的模块化方法承袭官方推荐:

技术分享

1. index.js

import Vue from ‘vue‘
import Vuex from ‘vuex‘
import * as actions from ‘./actions‘
import * as getters from ‘./getters‘
import a from ‘./modules/a‘
import b from ‘./modules/b‘

Vue.use(Vuex)

export default new Vuex.Store({
  actions,
  getters,
  modules: {
    a,
    b
  }
})

  这个整个store模块的入口文件,做一个所有模块的整合再export出去;

这里面有个所谓全局的getters和actions,如果没有也可以不加;模块内部的 action、mutation、和 getter 仍然注册在全局命名空间,所以其实任何子组件都是可以调用所有模块的store

2. mutations-types.js 

这个js就是定义一些常量

export const CHANGE_A = ‘CHANGE_A‘
export const CHANGE_B = ‘CHANGE_B‘

3. 两个案例模块,a.js/b.js

import * as types from ‘../mutation-types‘

// initial state
const state = {
  aa:‘aa‘
}

// getters
const getters = {
  aa: state => `from getters:${state.aa}`
}

// actions
const actions = {
  addStringA ({ commit, state }, str) {
    commit(types.CHANGE_A, { str })
  }
}

// mutations
const mutations = {
  [types.CHANGE_A] (state, { str }) {
    state.aa += str
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

  这里就是一个模块的store,可以看到和我们上面的单页面vuex.js很像

4. 子组件调用

<template>
  <div id="app">
    <myHeader></myHeader>
    <div id="container" @click="addStringA(‘nnnn‘)">
    {{aa}}=={{bb}}
    </div>
  </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from ‘vuex‘

export default { 
  name:‘app‘,  
 
  computed:{  
    ...mapGetters([
                 ‘aa‘,‘bb‘
    ]),   
    promotionInfo(){}
  },
  methods:{ 
    // ...mapActions([
    //              ‘Gaction‘,‘addStringA‘
    // ]),
    addStringA(str){
      this.$store.dispatch(‘addStringA‘, str)
    }
  }
}
</script>

  在methods里面,分别用mapActions和dispatch的方式触发action,结果都是一样的

 

vue系列——组件数据通讯(二)

标签:基础   render   项目   stat   更新   命名   str   lan   常量   

原文地址:http://www.cnblogs.com/webLilingyun/p/6560637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!