uniapp中使用vuex(解决uniapp无法在data和template中获取vuex数据问题)

uniapp中使用vuex(解决uniapp无法在data和template中获取vuex数据问题)

1. uniapp中引入vuex

1 .在根目录下新建文件夹store,在此目录下新建index.js文件(uniapp中有自带vuex插件,直接引用即可)

在这里插入图片描述

其中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: {
    
    
	     setHasLogin(context) {
    
    
	      context.commit('setHasLogin')
	    }
    },
    getters: {
    
    
    	reverseLoginStatus(state) {
    
    
	      return state.hasLogin = !state.hasLogin
	    }
    }
})
  1. 在main.js中导入
import Vue from 'vue'
import App from './App'
//这里
import store from '@/store/index.js'
Vue.config.productionTip = false
//这里
Vue.prototype.$store = store
App.mpType = 'app'
 
const app = new Vue({
    
    
    ...App,
//这里
	store,
})
app.$mount()

2. uniapp中使用vuex

2.1 this.$store直接操作

//获取state中的值
this.$store.state.loginStatus

//修改state中的值,这里需要在mutations中定义修改的方法,如上setHasLogin
this.$store.commit('setHasLogin', true);

//调用actions中的方法,这里需要在actions中定义方法
this.$store.dispatch('setHasLogin')

//调用getters中的方法,这里需要在getters中定义方法
this.$store.getters.reverseLoginStatus

2.2 通过mapState, mapGetters, mapActions, mapMutations

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

3. 解决uniapp无法在data和template中获取vuex数据问题

需要注意的是,原生vuex用多了很容易顺手,this.$store.state直接就用,这里直接写在dom里是获取不到的。

//直接在temmplate中使用是无法获取到的
<temmplate>
	<div>{
    
    {
    
    this.$store.state.loginStatus}}</div>
</temmplate>

解决办法(如上述2.2的使用):

//这样就可以使用啦
<temmplate>
	<div>{
    
    {
    
    this.$store.state.loginStatus}}</div>
</temmplate>


<script>
 	export default {
    
    
		computed:{
    
    
			loginStatus() {
    
    
			    return this.$store.state.loginStatus
			},
		}
	}
</script>

猜你喜欢

转载自blog.csdn.net/qq_58648235/article/details/130447049
今日推荐