uniapp中怎么使用vuex

发布时间:2023-05-04 17:07:16 作者:iii
来源:亿速云 阅读:115

本文小编为大家详细介绍“uniapp中怎么使用vuex”,内容详细,步骤清晰,细节处理妥当,希望这篇“uniapp中怎么使用vuex”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

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

1. uniapp中引入vuex

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

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”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. uniapp组件uni-popup弹出层怎么用
  2. uni-app生成微信小程序报错怎么解决

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

uniapp vuex

上一篇:Vercel数据库存储服务怎么使用

下一篇:Vue怎么实现字母验证码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》