javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > uniapp使用vuex

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

作者:无·糖

这篇文章主要介绍了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
	    }
    }
})

在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>

到此这篇关于uniapp中使用vuex(解决uniapp无法在data和template中获取vuex数据问题)的文章就介绍到这了,更多相关uniapp使用vuex内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文