小型项目中可以这样替代vuex

1,617 阅读1分钟

平时小项目中有可能需要一些全局共享的响应式数据,使用vuex可能会稍微麻烦一点。下面分享一个个人在平时小项目中的使用替代vuex的代码段。

import Vue from 'vue'

const state = Vue.observable({
    user: {
        account: '',
        name: '',
    },
    channelId: '',
})

const store = {
    state: state,
    dispatch: function (method, ...args) {
        return this.methods[method].apply(this, [...args])
    },
    methods: {
        login: function (callBackUrl = '') {
            return api.userLogin()
        },

        updateUserInfo(user) {
            this.state.user = Object.assign(this.state.user, user)
        },
    },
}

store.commit = store.dispatch

export default store

在main.js中引入自定义store

import Vue from 'vue'
import store from '@/store'

//简单演示,勿喷
store.dispacth('login').then(res=>{

})

Vue.prototype.$store=store

//有时我们可能多个页面会使用到user的信息,可以单独挂载,然后各个页面直接this.$user就可以直接使用
Vue.prototype.$user=store.state.user

到此,水完了这篇文章~