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(){