天天看点

关于vueX如何定义和使用

目录

    • 如何定义?
      • store.js
      • app.js
    • 如何使用?
      • 1. state 的调用
      • 2. mutations 的调用
      • 3. actions 的调用
      • 4. getters 的调用
      • 5. modules的使用

如何定义?

store.js

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

Vue.use(Vuex)
// 手动引入modules
import bus from './module/bus'
import app from './module/app'

export default new Vuex.Store({
  // state: 储存共享的数据源,仅可以被 mutations 更改
  state: {
    count: 5
  },
  // mutations: 同步函数,`唯一` 可以 `同步` 修改 state的 地方
  mutations: {
    // 第一个参数为 state 对象,可以通过 state 访问到其中的数据,从第二个参数开始往后,所有的形参都为调用函数所传传递的参数,用以方便操作函数。
    add(state, payload) {
      return state.count += payload
    },
    reduce(state, payload) {
      return state.count -= payload
    }
  },
  // actions: 异步函数,异步的修改 state,但其不能直接改,最终必须 commit 到指定 mutations 中
  actions: {
    setCount(store) {
      setTimeout(() => {
        // commit 用来访问 mutations 中的同步函数
        // 格式为: store.commit("同步函数名", 传递的参数)
        // 第一个参数默认为根对象, 之后的参数都为传递的实参
        store.commit("add", 100)
      }, 1000)
    }
  },
  // getters: vuex 的计算属性,数据源 计算而得到,类似computed。 优势:带缓存
  getters: {
    // 格式为:  return  计算结果
    // 第一个参数默认为 state
    newNum(state) {
      const newNum = state.count * 100
      return newNum
    }
  },
  modules: { // 子vuex状态模块注册
        namespaced: true, // 为了解决不同模块命名冲突的问题
        app,
        bus
    }
})

           

app.js

const state = {
    user: {}, // 需要管理的状态数据
}

const mutations = {
    setUser (state, val) {
            state.user = val
        }
}
const getters = {}
const actions = {}

export default {
    namespaced: true,
    state,
    mutations,
    getters,
    actions
}

           

如何使用?

在需要使用的组件中进行调用,调用方法分为 直接调用 和 映射使用

state、getters 都是映射在组件的 computed 中
    mutations、actions  都是映射在组件的 methods 中
           

1. state 的调用

  • 直接调用:
this.$store.state.变量名  
           
  • 映射使用 mapState
映射分为对象和数组,对象可以更改映射在当前页面的属性名
import { mapState } from 'vuex'
export default {
    computed: {
    	// 语法
        ...mapState(['state变量名']),// 不能改名
        ...mapState({ // 能改名
            计算属性名: 'state中变量名'
        })
        // 示例
        ...mapState(["count"]),
        ...mapState({ 
            num: 'count',
        })
    }
}
           

2. mutations 的调用

  • 直接调用:
  • 映射使用 mapMutations
import { mapMutations } from 'vuex'
export default {
    methods: {
        ...mapMutations(['mutations中函数名'])
    }
}
           

3. actions 的调用

  • 直接调用:
  • 映射使用 mapActions
import { mapActions } from 'vuex'
export default {
    methods: {
        ...mapActions(['actions函数名'])
    }
}
           

4. getters 的调用

  • 直接调用
this.$store.getters.计算属性的名字
           
  • 映射使用 mapGetters
import { mapGetters } from 'vuex'
export default {
    computed: {
        ...mapGetters(['getters中计算属性的名字'])
    }
}
           

5. modules的使用

// 使用模块中的mutations、getters、actions时候,要加上模块名,例如使用commint执行mutations时
// 格式: 模块名/模块中的mutations
this.$store.commit("app/setUser", user)

// 获取属性时同样加上模块名
this.$store.state.app.user 

           

继续阅读