欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

uniapp中使用vuex的過程(解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題)

 更新時(shí)間:2023年05月04日 16:57:45   作者:無·糖  
這篇文章主要介紹了uniapp中使用vuex(解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

uniapp中使用vuex(解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題)

1. uniapp中引入vuex

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

在這里插入圖片描述

其中index.js內(nèi)容為

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
    state: {
        hasLogin: false, // 登錄狀態(tài)
        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中導(dǎo)入

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);
//調(diào)用actions中的方法,這里需要在actions中定義方法
this.$store.dispatch('setHasLogin')
//調(diào)用getters中的方法,這里需要在getters中定義方法
this.$store.getters.reverseLoginStatus

2.2 通過mapState, mapGetters, mapActions, mapMutations

//頁面內(nèi)導(dǎo)入vuex的mapState跟mapMutations方法
import { mapState, mapMutations } from 'vuex'
computed: {
  ...mapState(['hasLogin'])
}
methods: {
  ...mapMutations(['setHasLogin']),
}

3. 解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題

需要注意的是,原生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>

到此這篇關(guān)于uniapp中使用vuex(解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題)的文章就介紹到這了,更多相關(guān)uniapp使用vuex內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論