uniapp中使用vuex的過程(解決uniapp無法在data和template中獲取vuex數(shù)據(jù)問題)
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.reverseLoginStatus2.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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript實現(xiàn)文本框標簽驗證的實例代碼
這篇文章主要介紹了javascript實現(xiàn)文本框標簽驗證的實例代碼,需要的朋友可以參考下2018-10-10
JavaScript高級程序設(shè)計 錯誤處理與調(diào)試學(xué)習(xí)筆記
JavaScript高級程序設(shè)計 錯誤處理與調(diào)試學(xué)習(xí)筆記,學(xué)習(xí)js的朋友可以參考下。2011-09-09
JS檢測window.open打開的窗口是否關(guān)閉
在開發(fā)中遇到需要在打開窗口的同時給父窗口添加遮罩防止用戶誤操作,而在窗口關(guān)閉時需要去掉父窗口的遮罩以便用戶操作。所以可以利用setInterval()來周期性的檢測打開的窗口是否關(guān)閉2017-06-06

