vuex的原理图
安装:
npm i vuex安装的就是vue3的版本vuex4,vuex4只能在vue3中使用;所以如果时vue2使用的话,需下载vuex3版本,在终端中输入命令npm i vue@3
使用vuex:
首先在src文件夹下新建store文件夹,
store文件夹中创建index.js文件,内容如下,
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入store
import store from './store'
//关闭Vue的生产提示
Vue.config.productionTip = false//创建vm
new Vue({el: '#app',render: h => h(App),// store:'store'//可以简写:,所以VM和VC中都有$storestore
})
main.js中内容如下
Index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
}//准备mutations-用于操作数据(state)
const mutations = {
}
//准备state-用于存储数据
const state = {
}
const getters = {
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
})
小案例,实现效果:
代码:(main.js、store(index.js)、Count.vue、APP.vue)
main.js同上
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)const actions = {/* jia(context, value) {context.commit('JIA', value)},jian(context, value) {context.commit('JIAN', value)}, */jiaOdd(context, value) {if (context.state.sum % 2) {context.commit('JIA', value)}},jiaWait(context, value) {setTimeout(() => {context.commit('JIA', value)}, 500);},}//准备mutations-用于操作数据(state)
const mutations = {JIA(state, value) {state.sum += value},JIAN(state, value) {state.sum -= value},
}
//准备state-用于存储数据
const state = {sum: 0,school: 'henan',subject: 'physical'
}
const getters = {bigSum(state) {return state.sum * 10}
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
})
App.vue:
<template><div><Count/></div>
</template><script>
import Count from './components/Count';
export default {name:'App',components:{Count},
}
</script>
Count.vue:
<template><div><!-- <h1>当前求和为:{{ $store.state.sum }}</h1> --><h1>当前求和为:{{ sum }}</h1><!-- <h1>当前求和为:{{ $store.getters.bigSum}}</h1> --><h1>当前求和为:{{ bigSum}}</h1><!-- <h3>我在{{$store.state.school}},学习{{ $store.state.subject }}</h3> --><h3>我在{{school}},学习{{ subject }}</h3><select v-model.number="n"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="increment">+</button><button @click="decrement">-</button><button @click="incrementOdd">当前求和为奇数再加</button><button @click="incrementWait">等一等再加</button></div>
</template><script>
import { mapState,mapGetters } from 'vuex';
export default {name:'Count',data(){return {n:1,}},computed:{//借助mapState生成计算属性,从state中读取数据(对象写法)// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'})//借助mapGetter生成计算属性,从getters中读取数据(数组写法)...mapState(['sum', 'school', 'subject']),...mapGetters(['bigSum'])},methods:{increment(){this.$store.commit('JIA', this.n)},decrement(){this.$store.commit('JIAN', this.n)},incrementOdd(){if(this.$store.state.sum % 2){this.$store.dispatch('jiaOdd', this.n)}},incrementWait(){this.$store.dispatch('jiaWait', this.n)},},mounted(){// const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})// console.log(x);}
}
</script><style>
button {margin-left: 20px;
}
</style>