本文小编为大家详细介绍“uniapp中怎么使用vuex”,内容详细,步骤清晰,细节处理妥当,希望这篇“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()
//获取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
//页面内导入vuex的mapState跟mapMutations方法
import { mapState, mapMutations } from 'vuex'
computed: {
...mapState(['hasLogin'])
}
methods: {
...mapMutations(['setHasLogin']),
}
需要注意的是,原生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”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/qq_58648235/article/details/130447049