目录

概念

搭建环境

基本使用(举例)

getters

四个map方法

模块化和命名空间


概念:

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

Github地址:https://github.com/vuejs/vuex

使用场景:多个组件依赖同一状态、来自不同组件的行为需要变更同一状态(多组件需要共享数据时)。

Vue笔记(五)vuex

搭建环境:

因为vuex已经更新到4版本,而vue2与vuex3匹配,所以安装时运行npm i vuex@3

1.创建文件:

Vue笔记(五)vuex

 index.js

// 此文件用于创建vuex中最核心的store
// 引入核心库Vue
import Vue from 'vue';
// 引入vuex
import Vuex from 'vuex'
// 应用vuex插件
Vue.use(Vuex);
// 准备actions,用于响应组件中的动作
const actions={}
// 准备mutations,用于操作数据(state)
const mutations={}
// 准备state,用于存储数据
const state={}
// 创建并暴露store
export default new Vuex.Store({
// const store = new Vuex.Store({
    actions,// actions:actions,
    mutations,// mutations:mutations,
    state,// state:state,
})
// 暴露store
// export default store;

2.在main.js中创建vm时传入store配置项

// 引入Vue
import Vue from 'vue';
// 引入App组件
import App from './App.vue';
// 引入store
import store from './store' // import store from './store/index.js'
Vue.config.productionTip = false;
new Vue({
    el:'#app',
    // 将App组件放入容器中
    render:h=>h(App),
    store,// store:store,
})

为什么不能在main.js中import并use(vuex):

程序执行时会将import语句提升到最前面执行,读完import的东西才会接着读这个文件下面的内容;而程序必须先use(Vuex)再读store中的内容也就是main.js中的import store;所以采用如上写法,import和use(vuex)放在store中,就能保证程序先use(Vuex)再读store内其余内容。

基本使用(举例):

1.初始化数据

组件:.vue

<template>
    <div>
        <h1>当前求和:{{$store.state.sum}}</h1><br>
        <select v-model="n">
            <!-- value前加上":",引号里的值当成js表达式解析
            如果不加,value里的值就会解析成字符串,做拼串操作 -->
            <option :value="1">1</option>
            <option :value="2">2</option>
            <option :value="3">3</option>
        </select>
        <button @click="inc()">+</button>  
        <button @click="dec">-</button>  
        <button @click="oddInc">当前求和为奇数时加</button>  
        <button @click="waitInc">延迟3s加</button>
    </div>
</template>
<script>
export default {
    name:'Search',
    data() {
        return {
            n:1,
        }
    },
    methods: {
        inc(){
            this.$store.commit('INC',this.n)
        },
        dec(){
            this.$store.commit('DEC',this.n)
        },
        oddInc(){
            this.$store.dispatch('oddInc',this.n)
        },
        waitInc(){
            this.$store.dispatch('waitInc',this.n)
        }
    },
}
</script>
<style>
select,button{
    margin: 3px;
}
</style>

index.js

import Vue from 'vue';
import Vuex from 'vuex'
Vue.use(Vuex);
// 准备actions,用于响应组件中的动作
const actions={
    // inc(context,value){
    //     context.commit('INC',value)
    // },
    // dec(context,value){
    //     context.commit('DEC',value)
    // }, 这部分可以直接在组件中实现
    oddInc(context,value){
        if(context.state.sum%2)
        context.commit('INC',value)
    },
    waitInc(context,value){
        setTimeout(() => {
            context.commit('INC',value)
        }, 3000);
    },
}
// 准备mutations,用于操作数据(state)
const mutations={
    INC(state,value){
        state.sum+=value;
    },
    DEC(state,value){
        state.sum-=value
    }
}
// 准备state,用于存储数据
const state={
    sum:0,
}
// 创建并暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
})

Vue笔记(五)vuex

2.组件中读取vuex中的数据:$store.state.sum

3.组件中修改vuex中的数据:$store.dispatch(‘action中的方法名’,数据)或$store.commit(‘mutation中的方法名’,数据)

4.若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

getters:

当state中的数据需要经过加工后再使用时,可以使用getters加工

在index.js中追加getters的配置:

... ...

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

const getters={

    bigSum(state){

        return state.sum*10

    }

}

// 创建并暴露store

export default new Vuex.Store({

    ... ... ,

    getters

})

组件中读取数据:

$store.getters.bigSum

四个map方法:

mapState方法:用于帮助我们映射state中的数据为计算属性。

mapGetters方法:用于帮助我们映射getters中的数据为计算属性。

mapActions方法:用于帮助我们生成与action对话的方法,即包含$store.dispatch(xxx)的函数。

mapMutations方法:用于帮助我们生成与mutations对话的方法,即包含$store.commit(xxx)的函数。

mapActions与mapMutations使用时,若要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

index.js

import Vue from 'vue';
import Vuex from 'vuex'
Vue.use(Vuex);
// 准备actions,用于响应组件中的动作
const actions={
    oddInc(context,value){
        if(context.state.sum%2)
        context.commit('INC',value)
    },
    waitInc(context,value){
        setTimeout(() => {
            context.commit('INC',value)
        }, 3000);
    },
}
// 准备mutations,用于操作数据(state)
const mutations={
    INC(state,value){
        state.sum+=value;
    },
    DEC(state,value){
        state.sum-=value
    }
}
// 准备state,用于存储数据
const state={
    sum:0,
    name:'marling',
    address:'枫林大街268号'
}
// 准备getters,用于将state中的数据进行加工
const getters={
    bigSum(state){
        return state.sum*10
    }
}
// 创建并暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

.vue

<template>
    <div>
        <h1>当前求和:{{sum}}</h1>
        <h2>当前求和*10:{{bigSum}}</h2>
        <h3>姓名:{{name}},地址:{{address}}</h3>
        <select v-model="n">
            <option :value="1">1</option>
            <option :value="2">2</option>
            <option :value="3">3</option>
        </select>
        <button @click="INC(n)">+</button>  
        <button @click="dec(n)">-</button>  
        <button @click="oddInc(n)">当前求和为奇数时加</button>  
        <button @click="waitInc(n)">延迟3s加</button>
    </div>
</template>
<script>
import {mapGetters, mapState,mapMutations,mapActions} from 'vuex'
export default {
    name:'Search',
    data() {
        return {
            n:1,
        }
    },
    methods: {
        // inc(){
        //     this.$store.commit('INC',this.n)
        // },
        // dec(){
        //     this.$store.commit('DEC',this.n)
        // },
        // 借助mapMutations生成对应的方法,方法中会调用commit去练习mutations(对象写法)
        ...mapMutations({dec:'DEC'}),
        // 借助mapMutations生成对应的方法,方法中会调用commit去练习mutations(数组写法)
        ...mapMutations(['INC']),
        // oddInc(){
        //     this.$store.dispatch('oddInc',this.n)
        // },
        // waitInc(){
        //     this.$store.dispatch('waitInc',this.n)
        // }
        // 借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
        ...mapActions({oddInc:'oddInc'}),
        // 借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)
        ...mapActions(['waitInc'])
    },
    computed:{
        // sum(){
        //     return this.$store.state.sum
        // },
        // name(){
        //     return this.$store.state.name
        // },
        // address(){
        //     return this.$store.state.address
        // },
        // 借助mapState生成计算属性,从state中读取数据(对象写法)
        // "..."表示把每一项展开
        // ...mapState({he:'sum',mingzi:'name',dizhi:'address'}),
        // 借助mapState生成计算属性,从state中读取数据(数组写法)
        ...mapState(['sum','name','address']),
        // bigSum(){
        //     return this.$store.getters.bigSum
        // }
        // 借助mapGetters生成计算属性,从state中读取数据(对象写法)
        // ...mapGetters({bigSum:'bigSum'})
        // 借助mapGetters生成计算属性,从state中读取数据(数组写法)
        ...mapGetters(['bigSum'])
    },
    // mounted(){
    //     const x=mapState({he:'sum',mingzi:'name',dizhi:'address'})
    //     const x=mapState(['sum','name','address'])
    // }
}
</script>
<style>
select,button{
    margin: 3px;
}
</style>

Vue笔记(五)vuex

模块化和命名空间:

可以让代码更好维护,让多种数据分类更加明确。

store.js

const countAbout={
    namespaced:true,//开启命名空间
    state:{x=1},
    mutations:{...},
    actions:{...},
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}
const personAbout={
    namespaced:true,//开启命名空间
    state:{x=1},
    mutations:{...},
    actions:{...},
}
const store=new Vuex.Store({
    modules:{
        countAbout,
        personAbout
    }
})

开启命名空间后,组件中读取state数据:

//直接读取

this.$store.state.personAbout.list

//借助mapState读取

...mapState('countAbout',['sum','name','address'])

开启命名空间后,组件中读取getters数据:

//直接读取

this.$store.getters['personAbout/firstPersonName']

//借助mapGetters读取

...mapGetters('countAbout',[''bigSum])

开启命名空间后,组件中调用dispatch:

//直接dispatch

this.$store.dispatch('personAbout/addPersonWang',person)

//借助mapActions

...mapActions('countAbout',{oddInc:'oddInc',waitInc:'waitInc'})

开启命名空间后,组件中调用commit:

//直接commit

this.$store.commit('personAbout/ADD_PERSON',person)

//借助mapMutations

...mapMutation('countAbout',{inc:'INC',dec:'DEC'})

(视频:B站尚硅谷)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。