在uniapp中使用vuex

1.安装vuex

npm install vuex --save

2.在根目录下新建一个store文件夹 ,然后创建js文件 index.js

index.js

//导入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
		show:true
	},
    mutations: {
		getshow(state,n){
			state.show=n
		}
	},
    actions: {
		getshow(context,args){
			context.commit('getshow',args);
		}
	}
})
export default store

3.在main.js中导入,挂载

import Vue from 'vue'
import App from './App'
import store from './store/index.js'  //导入

//把vuex定义为全局组件
Vue.prototype.$store = store

// #ifndef VUE3

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	store,    //挂载
    ...App
})

4.使用

<script>
import {mapState} from 'vuex'
export default{
	data() {
		return{
			
		}
	},
    mounted(){
        this.$store.dispatch('getshow',true)  //修改值
        console.log(this.$store.state.show)   //获取值
    }
}
</script>

取值的第二种方法:

<script>
import {mapState} from 'vuex'
export default{
	data() {
		return{
			
		}
	},
    //获取值
	computed:{
		...mapState({
			show:state=>state.show
		})
	},
    mounted(){
        console.log(this.show)   
    }
}
</script>

参考文章:uniapp中使用vuex_Smile_zxx的博客-CSDN博客_uniapp使用vuex

猜你喜欢

转载自blog.csdn.net/WeiflR10/article/details/126886630
今日推荐