uniApp 使用vuex

1、根目录创建store目录,创建index.js文件;

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

Vue.use(Vuex);


export default new Vuex.Store({
    state: {
        hasLogin: false, // 登录状态
        userInfo: {}, // 用户信息
    },
    mutations: {
        setHasLogin(state, value){
            state.hasLogin = value
            console.log(state.hasLogin)
        }
    },
    actions: {},
    getters: {}
})

 2、在mian.js 中挂载store

import Vue from 'vue'
import App from './App'
import store from './store'  

Vue.config.productionTip = false
Vue.prototype.$store = store

App.mpType = 'app'

const app = new Vue({
    ...App,
    store,
})
app.$mount()

3、uniapp中使用vuex

3.1 获取state中的值

this.$store.state.loginStatus

3.2 修改state中的值

这里需要在mutations中定义修改的方法,如上setHasLogin

this.$store.commit('setHasLogin', true);

3.3 调用actions中的方法

这里需要在actions中定义方法

this.$store.dispatch('',{number:123})

3.4 调用getters中的方法

这里需要在getters中定义方法

this.$store.getters.reverseLoginStatus

4、状态方法监控

//页面内导入vuex的mapState跟mapMutations方法
import { mapState, mapMutations } from 'vuex'
computed: {
  ...mapState(['hasLogin'])
}
methods: {
  ...mapMutations(['setHasLogin']),
}

猜你喜欢

转载自blog.csdn.net/qq_41954585/article/details/127744018
今日推荐