VUEX——组件之间共享数据的方式

432 阅读4分钟

官方文档:vuex.vuejs.org/zh/

以下三种vue数据共享的方式适合小范围内传值,如果是大范围频繁共享数据的话会显得力不从心;

1. 父向子传值: v-bind 属性绑定

2. 子向父传值: v-on 事件绑定

3. 兄弟组件之间共享数据: EventBus; on(接收数据的组件)/on(接收数据的组件)/ emit(发送数据的组件)

VUEX由此应运而生:

1. vuex是什么?

vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

2. 使用vuex统一管理状态的好处?

1)能够在vuex中集中管理共享的数据,易于开发和后期维护

2)能够高效地实现组件之间的数据共享,提高开发效率

3)存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步

3. 什么样的数据适合存储到vuex中?

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。(vuex与localstorage的区别:vuex对数据的修改是响应式的,无需页面刷新,storage中的数据需要手动刷新才会更新,更适合存在页面跳转时使用)

4. vuex的基本使用

1)安装vuex依赖包

npm install vuex --save

2)导入vuex包

import Vuex from 'vuex'
Vue.use(Vuex)

3) 创建store对象

const store = new Vuex.Store({
    state: { count: 0 } //state中存放的就是全局共享的数据
})

4)将store对象挂载到vue实例中 

new Vue({
    el: '#app',
    render: h => h(app),
    router,
    //将创建的共享数据对象挂载到vue实例中
    //所有的组件就可以直接从store中获取全局的数据了
    store
})

5. vuex的主要核心概念

  1. state: 提供唯一的公共数据源,所有共享的数据要统一放到store的state中进行存储

    //创建store数据源,提供唯一公共数据 const store = new Vuex.Store({ state: { count: 0 } })

组件访问state中数据的第一种方式:

this.$store.state.全局数据名称  //如果是在template的标签中用插值方式获取,可以省略'this'

访问state中数据的第二种方式:

//1.从 vuex 中按需导入 mapState 函数
import { mapState } from'vuex

通过刚刚导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性

//2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapState(['count']) //需要使用哪些数据,就放入哪些数据
}

2) mutation: 用于变更store中的数据(但mutation中不能执行异步操作,只能放在action中)

① 只能通过mutation变更store数据,不可以直接操作store中的数据,如在methods中直接调用this.$store.state.count++;

② 通过这种方式虽然操作起来稍微繁琐一点,但是可以集中监控所有数据的变化。

触发mutation的第一种方式:

// 定义mutation
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: { //mutations中可以定义事件处理函数
        add(state) { //方法的第一个参数永远是自身的state
            state.count++ //变更状态
        }
    }
})

// 触发mutation
methods: {
    handler1() {
        // commit专门用来调用某个mutations函数
        this.$store.commit('add')
    }
}

可以在触发mutations时传递参数:

// 定义mutation
const store = mew Vuex.Store({
    state: {
        count: 0
    },
    mutations: { //只有mutations中定义的函数,有权利直接更改state中的数据
        addN(state, step) {
            state.count += step
        }
    }
})

// 触发mutation
methods: {
    handler2() {
        // 在调用mutations函数时携带参数 3, mutations函数用第二个参数 step 接收
        this.$store.commit('addN', 3)
    }
}

触发mutation的第二种方式:

// 1.从 vuex 中按需倒入 mapMutations 函数
import { mapMutations } from 'vuex

通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法

// 2.将指定的mutations函数,映射为当前组件的 methods 函数
methods: {
    ...mapMutations(['add', 'addN']), //这样即可像调用methods一样调用mutations方法
    handler(){
        this.add(),
        this.addN(2)
    }
}

3) action: 用于处理异步任务。如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是在action中还是要通过触发mutation的方式间接变更数据。

触发actions的第一种方式:

//定义action
const store = new Vuex.Store({
    mutations: {
        add(state){
            state.count++
        }
    },
    actions: { //actions不能直接修改state中的数据,必须通过context.commit()去触发mutations
        addAsync(context){ //异步函数
            setTimeout(()=>{
                context.commit('add')
            }, 1000)
        }
    }
})

//触发action
methods: {
    handler(){
        //触发actions的第一种方式
        this.$store.dispatch('addAsync') //dispatch专门用来调用actions中的函数
    }
}

触发actions异步任务时携带参数:

// 定义action
const store = mew Vuex.Store({
   mutations: {
        addN(state, step){
            state.count += step
        }
   },
   actions: { 
       addNAsync(context, step) {
           setTimeout(()=> {
               context.commit('addN', step)
           }, 1000)
       }
   }
})

// 触发action
methods: {
    handler2() {
        // 在调用异步函数时携带参数 5,actions中用第二个参数 step 接收
        this.$store.dispatch('addNAsync', 5)
    }
}

触发actions的第二种方式:

//1.从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'

通过导入的mapActions函数,将需要的actions函数映射为当前组件的methods方法;元素标签上可以直接绑定click事件调用该方法,而无须在methods重复定义

//2.将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
    ...mapActions(['addAsync', 'addNAsync'])
}

4) getter:用于对store中的数据进行加工处理形成新的数据。getter不会修改store中的原数据,只起到包装数据的作用。

① Getter可以对store中已有的数据加工处理之后形成新的数据,类似vue的计算属性。

② Store中数据发生变化,getter的数据也会跟着变化。

//定义getter
const store = new Vuex.Store({
    state: {
        count: 0
    },
    getters: {
        showNum: state => {
            return '当前最新的数量是【' + state.count + '】'
        }
    }
})

使用getters的第一种方式:

this.$store.getters.方法名  //在标签上用插值的方式直接调用可省略'this'

使用getters的第二种方式:

import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['showNum'])
}

(仅为个人学习总结www.bilibili.com/video/BV1h7…