Vuex模块化

npm install vuex -S

文件目录

|-- src
    |-- store  // 存放vuex相关文件
    |    |-- modules
    |    |-- |--    app.js
    |    |-- |--    user.js
    |    |-- getters.js
    |    |-- index.js

modules/app.js

// app.js
// 由于是模块化封装, 两种写法
// 1.直接通过mutations修改size, 可以使用 this.$store.commit('app/SET_SIZE', 'large')
// 2.通过actions修改size,可以使用 this.$store.dispatch('app/setSize', 'large')
const state = {
	size: 'small',
	sidebar: {
		hide: true
	}
}
const mutations = {
    SET_SIZE: (state, size) => {
        state.size = size
    },
    SET_SIDEBAR_HIDE: (state, status) {
    	state.sidebar.hide = status
	}
}
const actions = {
    setSize({commit}, size) {
        commit('SET_SIZE', size)
    },
    togglesSideBarHide({commit}, status) {
        commit('SET_SIDEBAR_HIDE', status)
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}

getters

// getters.js
const getters = {
    token: state => state.user.token,
    size: state => state.app.size
}

export default getters

index.js

// index.js
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import user from './modules/user'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        app,
        user
    },
    getters
})

export default store

修改state方法 -- mutations

this.$store.commit('app/SET_SIZE', 'large') // vue文件

修改state方法 -- actions

this.$store.dispatch('app/setSize', 'large') // vue文件

mapGetters

import { mapGetters } from 'vuex'

// 前提是需要在getters.js中声明
computed: {
    ...mapGetters['token']
},
created() {
    console.log(this.token)
}

mapState

import { mapState } from 'vuex'

computed: {
    ...mapState({
        token: (state) => state.user.token
    })
},
created(){
    console.log(this.token)
}

mapMutations/mapActions

import { mapMutations, mapActions } from 'vuex'

methods: {
    ...mapMutations({
        setsize: 'app/SET_SIZE'
    }),
    ...mapActions({
        actions_setSize:'app/setSize'
    }),
    btnClick() {
       // this.$store.commit('app/SET_SIZE', 'large') === this.setsize('large')
        this.setsize('large')
    },
    btnClick2() {
        this.actions_setSize('large')
    }
}

this.$store为undefined情况

  • vuex 和 vue 版本号不对应, vue2 对应vuex3, vue3 对应vuex4(去package.json文件中查看)

  • store.js中 new Vuex.Store() Store 要大写 ,Vuex.store这种写法也会报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值