uniapp で vuex を使用する

1. vuex をインストールする

npm install vuex --save

2. ルート ディレクトリに新しいストア フォルダを作成し、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>

値を取得する 2 番目の方法:

<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 blog _uniapp uses vuex

Guess you like

Origin blog.csdn.net/WeiflR10/article/details/126886630