Vuex
配置vuex开发环境
vue2对应vuex@3版本
vue3对应vuex@4版本
安装时需要注意
在main文件中写到如下:
import Vue from 'vue'
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
import Vuex from 'vuex'
import store from './store/index'
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
new Vue({
store:store,
render: h => h(App),
}).$mount('#app')
在src文件夹下添加store文件夹,index.js文件
//改文件用于创建vuex中的store
import Vue from "vue";
import Vuex from "vuex";
//准备actions——用于响应组件中的动作
Vue.use(Vuex)
const actions={
}
//mutations———用于操作数据(state)
const mutations={
}
//state——用于存储数据
const state={
}
//创建store
const store = new Vuex.Store({
actions:actions,
mutations:mutations,
state:state,
});
//暴露store
export default store;
以count为例子,展示其中代码
count.vue中代码
<template>
<div>
<h1>当前求和为:{{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increament">+</button>
<button @click="decreament">-</button>
<button @click="increamentOdd">当前求和为奇数再加</button>
<button @click="increamentWait">稍后再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data(){
return{
n:1,
}
},
methods:{
increament(){
this.$store.dispatch('jia',this.n)
},
decreament(){
this.$store.dispatch('jian',this.n)
},
increamentOdd(){
this.$store.dispatch('jiaOdd',this.n)
},
increamentWait(){
this.$store.dispatch('jiaWait',this.n)
}
}
}
</script>
index.js中代码
//改文件用于创建vuex中的store
import Vue from "vue";
import Vuex from "vuex";
//准备actions——用于响应组件中的动作
Vue.use(Vuex)
const actions={
jia:function (context,value) {
context.commit('JIA',value)
},
jian:function (context,value) {
context.commit('JIAN',value)
},
jiaOdd:function (context,value) {
if(context.state.sum % 2){
context.commit('JIA',value)
}
},
jiaWait:function (context,value) {
setTimeout(()=>{
context.commit('JIA',value)
},500)
}
}
//mutations———用于操作数据(state)
const mutations={
JIA:function (state,value) {
state.sum +=value
},
JIAN:function (context,value) {
state.sum -=value
}
}
//state——用于存储数据
const state={
sum:0,
}
//创建store
const store = new Vuex.Store({
actions:actions,
mutations:mutations,
state:state,
});
//暴露store
export default store;
开发者工具与vue的保持一致,在浏览器汇总vue插件进行查看
其可以查看mutation的内容与state中的内容
getters
//准备getters——用于将state中的数据进行加工
const getters={
bigSum(state){
return state.sum*10
}
}
在源文件中的访问方式
<h3>当前求和放大十倍:{{$store.getters.bigSum}}</h3>
mapState和mapGetters
在js添加如下代码,即可直接在标签中使用如:he,xuexiao等内容替代$store.state.sum等内容
import {mapState} from 'vuex'
//对象写法
computed:{
...mapState({he:'sum',xuexiao:'school',xueke:'try'})
...mapGetters(bigsum:'bigSum')
}
//数组写法,访问时使用数组中的名称进行访问
computed:{
...mapState(['sum','school','try'])
...mapGetters(['bigSum'])
}
mapMutations 、mapActions同理
多组件共享数据
- 本文链接:https://archer-lan.github.io/2023/11/20/Vuex%E9%85%8D%E7%BD%AE%E4%B8%8E%E4%BD%BF%E7%94%A8/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。