美文网首页
vuex4.0 使用

vuex4.0 使用

作者: 小李不小 | 来源:发表于2021-06-16 14:46 被阅读0次

    useStore使用

    注意:以下所有测试用例均适用了命名空间,state、getters、mutations、actions均在user这个module里面

    安装

    安装:npm install vuex@next --save
    

    一、准备工作
    1、准备user.js文件
    在store文件夹下生成一个module文件夹,文件夹里面生成user.js文件,文件内容如下:

    let state = {
             username: 'admin',
             total: 0,
             accessToken: 'admin',
             avatar: '随意设置',
             rolename: '随意设置',
             userList: [{ name: 'admin', age: 29 }]
         },
         getters = {
             accessToken: state => state.accessToken,
             username: state => state.username,
             rolename: state => state.rolename,
             avatar: state => state.avatar,
             userList: state => state.userList,
             total: state => state.total
         },
         mutations = {
             setAccessToken (state, accessToken) {// 设置accessToken
                state.accessToken = accessToken
            },
            setUsername (state, username) {// 设置用户名
                state.username = username
            },
            setRolename (state, rolename) {// 设置权限名
                state.rolename = rolename
            },
            setAvatar (state, avatar) {// 设置头像
                state.avatar = avatar
            },
            setUserList (state, list) {// 设置用户列表
                state.userList = list
            },
            setTotal (state, total) {
                state.total = total
            }
         },
         actions = {
             testActions ({ commit }, num) {
                 setTimeout(() => {
                     commit('setTotal', num)
                     console.log(num)
                 }, 2000)
             }
         };
    export default { state, getters, mutations, actions }
    

    2、修改store/index.js文件

    import { createStore } from 'vuex'
    let files = require.context('./modules', false, /\.js$/),
        modules = {};
    files.keys().forEach((key) => {
        modules[key.replace(/\.\/|\.js/g, '')] = files(key).default
    })
    // 导入所有 vuex 模块,自动加入namespaced:true,用于解决vuex命名冲突
    Object.keys(modules).forEach(key => {
        modules[key]['namespaced'] = true
    })
    
    export default createStore({
        modules
    })
    
    1,获取整个state
    获取: userStore = computed( () => store.state.user )
    使用: userStore.value.username
    插值式中使用: userStore.username
    
    2,获取单个state
    获取: username = computed( () => store.state.user.username )
    使用: username.value
    插值式中使用: username
    
    3,获取整个getters
    获取: getters = computed( () => store.getters )
    使用: getters.value[“user/username”]
    插值式中使用: getters[“user/username”]
    

    4,获取单个getters

    获取: gUsername = computed( () => store.getters[“user/username”] )
    使用: gUsername.value
    插值式中使用: gUsername
    
    5,mutations的使用
    方式一、直接调用 store.commit(“user/setTotal”, 20)
    方式二、
    let totalNum = ref(30),
    setTotal = totalNum => store.commit(“user/setTotal”, totalNum);// 声明变量
    setTotal(totalNum.value)// 执行方法
    
    6,actions的使用
    方式一、直接调用 store.dispatch(“user/testActions”, 20)
    方式二、
    let testNum = ref(30),
    testActions = testNum => store.dispatch(“user/testActions”, testNum);// 声明变量
    testActions(testNum.value)// 执行方法
    

    测试代码usestore.vue文件内容(只展示了script里面的代码)

    import { ref, computed, onMounted } from 'vue'
    import { useStore } from 'vuex'
    export default {
        name: 'UsestoreCom',
        setup () {
               let store = useStore(),
                   userStore = computed( () => store.state.user ),// 获取整个state
                   username = computed( () => store.state.user.username ),// 获取单个state
                   getters = computed( () => store.getters ),// 获取整个getters
                   gUsername = computed(() => store.getters['user/username']),//获取单个getters
                   // mitations的使用方式1
                   totalNum = ref(30),
                   setTotal = totalNum => store.commit('user/setTotal', totalNum),
                   // actions的使用方式1
                   testNum = ref(50),
                   testActions = testNum => store.dispatch("user/testActions", testNum);
               onMounted(() => {
                   // state
                   console.log(userStore.value.username)// admin
                   console.log(username.value)// admin
                   console.log('-----------------')
                   // getters
                   console.log(getters.value['user/username'])// admin
                   console.log(gUsername.value)// admin
                   console.log('-----------------')
                   // mutations
                   setTotal(totalNum.value)
                   // mitations的使用方式2
                   // store.commit('user/setTotal', 20)
                   console.log(store.getters['user/total'])// 30
                   console.log('-----------------')
                   // actions
                   testActions(testNum.value)
                   // actions的使用方式2
                   // store.dispatch('user/testActions', 40)
               })
            return {
                userStore,
                username,
                getters,
                gUsername
            }
        }
    }
    

    mapState、mapGetters、mapMutations、mapActions的使用

    本实例依然使用use module,直接上代码
    注意:这里只放置了js的实现方式,ts相关的实现方式会在之后更新

    import { computed, onMounted } from 'vue'
    import { mapState, mapGetters, mapMutations, mapActions, useStore } from 'vuex'
    export default {
           name: 'MapxxxCom',
        setup () {
               let store = useStore(),
                username2 = computed(() => store.getters['user/username']),
                // mapState
                states = mapState('user', ['accessToken', 'rolename']),
                accessToken = computed(states.accessToken.bind({ $store: store })),
                rolename = computed(states.rolename.bind({ $store: store })),
                // mapGetters
                getters = mapGetters('user', ['username', 'avatar']),
                username = computed(getters.username.bind({ $store: store })),
                avatar = computed(getters.avatar.bind({ $store: store })),
                // mapMutations
                mutations = mapMutations('user', ['setUserList', 'setTotal']),
                setUserList = mutations.setUserList.bind({ $store: store }),
                setTotal = mutations.setTotal.bind({ $store: store }),
                // mapActions
                actions = mapActions('user', ['testActions']),
                testActions = actions.testActions.bind({ $store: store });
            onMounted(() => {
                // // mapState
                // console.log('mapState accessToken: ' + accessToken.value)
                // console.log('mapState rolename: ' + rolename.value)
    
                // // mapGetters
                // console.log('mapGetters username: ' + username.value)
                // console.log('mapGetters avatar:' + avatar.value)
    
                // // mapMutations
                // setUserList([{ name: 'abc' }])
                // console.log(store.getters['user/userList'])
    
                // // mapActions
                // testActions()
            })
            return {
                // 
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:vuex4.0 使用

          本文链接:https://www.haomeiwen.com/subject/fnaxyltx.html