前端基础之vuex

发布于:2025-03-07 ⋅ 阅读:(11) ⋅ 点赞:(0)

是一个专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式管理(读或写),也是一种组件间通信的方式,适用于任意组件间的通信

什么时候使用vuex?
1.多组件依赖同一状态

2.来自不同组件的行为需要变更同一状态

Vuex结构图

在Actions中实现ajax请求发送或是需要进行一些加工逻辑处理,就可以在Actions中进行

基本配置

1.首先需要下载npm i jax

2.在src目录下创建一个store文件夹,创建一个index.js文件

// 该文件用于创建store

//引入Vuex

import Vuex from 'vuex'

//引入vue

import Vue from 'vue'

Vue.use(Vuex)

//准备actions——用于响应组件中动作

const actions={

   

}

//准备mutations——用于操作数据

const mutations={}

//准备state——用于存储数据

const state={

    sum:0,

}

//创建并且暴露store

export default new Vuex.Store({

    actions,

    mutations,

    state

})

3.在main.js中引入store.js,并使用

import Vue from 'vue'

import App from './App.vue'

import store from './store/index'

Vue.config.productionTip = false

Vue.use(store)

const vm= new Vue({

  render: h => h(App),

  beforeCreate(){

    Vue.prototype.$bus=this

  },

  store

}).$mount('#app')

console.log(vm)

实际使用

在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="increment">+</button>

    <button @click="decrement">-</button>

    <button @click="incrementOdd">当前求和为奇数再加:</button>

    <button @click="incrementWait">等一等再加</button>

  </div>

</template>

<script>

export default {

    name:'Count',

    data(){

        return{

         

            n:1,//用户选择

        }

    },

    methods:{

        increment(){           //我们可以直接使用Commit去调用Mutations中的方法,去绕过不需要业务逻辑处理的Actions

            this.$store.commit('JIA',this.n)

        },

        decrement(){

            this.$store.commit('JIAN',this.n)

        },

        incrementOdd(){

                this.$store.dispatch('jianOdd',this.n)

        },

        incrementWait(){

                this.$store.dispatch('jianWait',this.n)

        }

    },

   

}

</script>

<style scoped>

button{

    margin-left: 5px;

}

</style>

在store文件夹下的index.js中

// 该文件用于创建store

//引入Vuex

import Vuex from 'vuex'

//引入vue

import Vue from 'vue'

Vue.use(Vuex)

//准备actions——用于响应组件中动作

const actions={

    jianOdd(context,value){

        if(context.state.sum%2){

         context.commit('JIA',value)

        }

     

    },

    jianWait(context,value){

       setTimeout(()=>{

        context.commit('JIA',value)

       },500)

    },

}

//准备mutations——用于操作数据

const mutations={

    JIA(state,value){

      state.sum+=value

    },

    JIAN(state,value){

        state.sum-=value

    }

}

//准备state——用于存储数据

const state={

    sum:0,

}

//创建并且暴露store

export default new Vuex.Store({

    actions,

    mutations,

    state

})

getters配置项

如果我们需要对vuex中的数据进行一个复杂的逻辑计算,就可以配置一个getters配置项,这个配置项类似于之前的computed,配置完毕之后还需要将其进行暴露

// 该文件用于创建store

//引入Vuex

import Vuex from 'vuex'

//引入vue

import Vue from 'vue'

Vue.use(Vuex)

//准备actions——用于响应组件中动作

const actions={

    jianOdd(context,value){

        if(context.state.sum%2){

         context.commit('JIA',value)

        }

     

    },

    jianWait(context,value){

       setTimeout(()=>{

        context.commit('JIA',value)

       },500)

    },

}

//准备mutations——用于操作数据

const mutations={

    JIA(state,value){

      state.sum+=value

    },

    JIAN(state,value){

        state.sum-=value

    }

}

//准备state——用于存储数据

const state={

    sum:1,

}

//准备getters——用于将state中的数据进行加工

const getters={

    bigSum(state){

        return state.sum*10

    }

}

//创建并且暴露store

export default new Vuex.Store({

    actions,

    mutations,

    state,

    getters

})

在需要使用的地方使用$store.getters.bigSum进行引用

<template>

  <div>

    <h1>当前求和为{{$store.state.sum}}</h1>

    <h1>当前求和放大十倍为{{$store.getters.bigSum}}</h1>

    <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>

export default {

    name:'Count',

    data(){

        return{

         

            n:1,//用户选择

        }

    },

    methods:{

        increment(){           //我们可以直接使用Commit去调用Mutations中的方法,去绕过不需要业务逻辑处理的Actions

            this.$store.commit('JIA',this.n)

        },

        decrement(){

            this.$store.commit('JIAN',this.n)

        },

        incrementOdd(){

                this.$store.dispatch('jianOdd',this.n)

        },

        incrementWait(){

                this.$store.dispatch('jianWait',this.n)

        }

    },

   

}

</script>

<style scoped>

button{

    margin-left: 5px;

}

</style>

MapState与MapGetter

我们可以通过使用计算数据computer,来达到简写{{}}里面数值的作用

但是我们可以直接使用mapState与mapGetters来帮助我们生成代码

<template>

  <div>

    <h1>当前求和为{{sum}}</h1>

    <h1>当前求和放大十倍为{{bigSum}}</h1>

    <h1>我在{{school}},学习{{subject}}</h1>

    <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,//用户选择

        }

    },

    methods:{

        increment(){           //我们可以直接使用Commit去调用Mutations中的方法,去绕过不需要业务逻辑处理的Actions

            this.$store.commit('JIA',this.n)

        },

        decrement(){

            this.$store.commit('JIAN',this.n)

        },

        incrementOdd(){

                this.$store.dispatch('jianOdd',this.n)

        },

        incrementWait(){

                this.$store.dispatch('jianWait',this.n)

        }

    },

    computed:{

        //借助mapState生成计算属性——对象写法,keyvalue不要求统一

       // ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),

        //借助mapState生成计算属性——数组写法,keyvalue要求统一,并且可以简写

        ...mapState(['sum','school','subject']),

        /* ============================================== */

        //借助mapGetters生成计算属性——数组写法,keyvalue要求统一,并且可以简写

        ...mapGetters(['bigSum'])

    }

}

</script>

<style scoped>

button{

    margin-left: 5px;

}

</style>

也就是说,如果我们需要获取vuex中管理的数据,可以使用mapState来实现,如果该数据需要进行数据操作,可以使用mapGetters来实现

MapMutations与MapActions

如果我们需要去执行vuex中的Mutations与MapActions方法,可以使用MapMutations与MapActions来实现

<template>

  <div>

    <h1>当前求和为{{sum}}</h1>

    <h1>当前求和放大十倍为{{bigSum}}</h1>

    <h1>我在{{school}},学习{{subject}}</h1>

    <select v-model.number="n">

        <option value="1">1</option>

        <option value="2">2</option>

        <option value="3">3</option>

    </select>

    <button @click="JIA(n)">+</button>

    <button @click="JIAN(n)">-</button>

    <button @click="incrementOdd(n)">当前求和为奇数再加:</button>

    <button @click="incrementWait(n)">等一等再加</button>

  </div>

</template>

<script>

import { mapState, mapGetters,mapMutations,mapActions} from 'vuex';

export default {

    name:'Count',

    data(){

        return{

         

            n:1,//用户选择

        }

    },

    computed:{

        //借助mapState生成计算属性——对象写法,keyvalue不要求统一

       // ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),

        //借助mapState生成计算属性——数组写法,keyvalue要求统一,并且可以简写

        ...mapState(['sum','school','subject']),

        /* ============================================== */

        //借助mapGetters生成计算属性——数组写法,keyvalue要求统一,并且可以简写

        ...mapGetters(['bigSum'])

    },

    methods:{

       

        // incrementOdd(){

        //         this.$store.dispatch('jianOdd',this.n)

        // },

        // incrementWait(){

        //         this.$store.dispatch('jianWait',this.n)

        // },

        ...mapActions({incrementOdd:'jianOdd',incrementWait:'jianWait'}),

        /* 亲自写方法 */

        // increment(){           //我们可以直接使用Commit去调用Mutations中的方法,去绕过不需要业务逻辑处理的Actions

        //     this.$store.commit('JIA',this.n)

        // },

        // decrement(){

        //     this.$store.commit('JIAN',this.n)

        // },

        //借助mapMutations调用Commit去访问Mutations——对象写法

       // ...mapMutations({increment:'JIA',decrement:'JIAN'}),

         //借助mapMutations调用Commit去访问Mutations——数组写法

         ...mapMutations(['JIA','JIAN'])

    }

}

</script>

<style scoped>

button{

    margin-left: 5px;

}

</style>