vue.js.2.0 icon indicating copy to clipboard operation
vue.js.2.0 copied to clipboard

【Vuex】使用

Open Kelichao opened this issue 7 years ago • 1 comments

科普

  • vuex类似于全局数据仓库,需要通过其特定API改变,用于大型页面组件,页面间的数据通信

引入使用

import Vue from 'vue'
import Vuex from 'vuex'

// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex),调用了才能通过 this.$store访问
Vue.use(Vuex)

window.store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

// 触发方法
store.commit('increment')

// 取得值
store.state.count// 1
  • 如果注册在了vue实例中,则可以用 this.$store.state获取数据源

五个核心概念

  • State : 在 Vue 组件中获得 Vuex 状态
  • Getter: 可以认为是 store 的计算属性(返回值会根据它的依赖被缓存起来)
  • Mutation:Vuex 中的 mutation 非常类似于事件,用来进行对数据的改变
  • Action:类似于 mutation,不同在于1.Action 提交的是 mutation,而不是直接变更数据状态。2.可以包含任意异步操作。
  • Module:Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter

state 详情

// 最基础取法
this.$store.state.count

// 批量取,使用mapState 辅助函数
// 这家伙一般返回的是一个对象,平时都放在计算属性里
      // obj: {
        //     fn1: function() {

        //     },
        //     fn2: function() {

        //     }
        // }

 mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

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

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

mapState 用法1,当方法调用

        methods: {
            ...mapGetters({
                operuserStations: "recordoperuserStations"
            }),
        }

mapState用法2,计算属性

computed: mapState({
                operuserStations: "recordoperuserStations"
                }),
      )

独立使用

import { mapGetters, mapActions } from 'vuex';
var userDataCont = mapGetters({
    userData: 'recorduserData',
});
// 注意,要指向vue实例,不然报getter不存在
console.log(userDataCont.userData.call(vue).userCode);

Kelichao avatar Dec 15 '17 05:12 Kelichao

vue.use(vuex)

Kelichao avatar Dec 27 '19 08:12 Kelichao