Vue的全家桶 --- Vuex

Vuex的详解

1. Vue概述

1.1 组件之间共享数据的方式

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

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

  • 兄弟组件之间共享数据:EventBus

    • $on 接收数据的那个组件
    • $emit 发送数据的那个组件

1.2 Vuex是什么

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

1.3 使用Vuex统一管理状态的好处

  • 能够在vuex中集中管理共享的数据,易于开发和后期维护
  • 能够高效地实现组件之间的数据共享,提高开发效率
  • 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步

1.4 什么样的数据适合存储在Vuex中

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。

2. VueX的基本使用

1.安装vuex依赖包

npm install vuex --save

2.导入vuex包

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

3.创建store对象

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

4.将store对象挂载带vue实例中

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

3. Vuex的核心概念

3.1 核心概念概述

Vuex中的主要核心概念:

  • State
  • Mutation
  • Action
  • Getter

3.2 State

State 提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储

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

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

this.$store.state.全局数据名称

3.2 State

组件访问State中数据的第二种方式:

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

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

// 2. 将全局数据,映射为当前组件的计算属性
computed: {
    ...mapState(['count'])
}

3.3 Mutation

Mutation 用于变更Store中的数据

  • 只能通过mutation变更Store数据,不可以直接操作Store中的数据。
  • 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
// 定义 Mutation
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        add(state) {
            // 变更状态
            state.count++
        }
    }
})
// 触发mutation
methods: {
    handle1() {
        // 触发mutations 的第一种方式
        this.$store.commit('add')
    }
}

3.3 Mutation

可以触发mutations时传递参数:

// 定义 Mutation
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        addN(state, step) {
            // 变更状态
            state.count += step
        }
    }
})
// 触发mutation
methods: {
    handle2() {
        // 在调用 commit 函数
        // 触发 mutations 时携带参数
        this.$store.commit('addN', 3)
    }
}

3.3 Mutation

**this.$store.commit()**是触发mutations的第一种方式,触发mutations的第二种方式:

// 1. 从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex' 
// 2. 将指定的 mutations 函数,映射为当前组件的methods 函数
methods: {
    ...mapState(['add', 'addN'])
}

3.4 Action

Action 用于处理异步任务

如果通过异步操作变更数据,必须通过Action,而不能使用Mutaion,但是在Action 中还是要通过触发Mutation 的方式间接变更数据。

// 定义Action
const store = new Vuex.Store({
    // ...省略其他代码
    mutations: {
        add(state) {
            state.count++
        }
    },
    actions: {
        addAsync(context) {
            setTimeout(() => {
                context.commit('add')
            }, 1000)
        }
    }
})
// 触发 Action
methods: {
    handle() {
        // 触发 actions的 第一种方式
        // 这里的dispatch 函数,专门用来触发 Action
        this.$store.dispatch('addAsync')
    }
}

3.4 Action

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

// 定义Action
const store = new Vuex.Store({
    // ...省略其他代码
    mutations: {
        addN(state, step) {
            state.count += step
        }
    },
    actions: {
        addNAsync(context,step) {
            setTimeout((step) => {
                context.commit('addN', step)
            }, 1000)
        }
    }
})
// 触发 Action
method: {
    handle() {
        // 在调用 dispatch 函数
        // 触发 actions 时携带参数
        this.$store.dispatch('addNAsync', 5)
    }
}

3.4 Action

**this.$store.dispatch()**是触发actions 的第一种方式,触发actions 的第二种方式:

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

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

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

3.5 Getter

Getter 用于对Store 中的数据进行加工处理形成新的数据。

  • Getter 可以对Store 中已有的数据加工处理之后形成的新的数据,类似Vue的计算属性。
  • Store 中数据发生变化,Getter的数据也会跟着变化。
// 定义Getter
const store = new Vuex.state({
    state: {
        count: 0
    },
    getters: {
        showNum: state => {
            reture '当前最新的数量是【'+state.count + '】'
        }
    }
})

3.5 Getter

使用getters的第一种方式:

this.$store.getter.名称

使用getters的第二种方式:

import { mapGetters } from 'vuex'

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

四、基于Vuex的案例

用vue实现todoList功能

开发准备

  • antd-vue组件库
  • vuex

需求分析

  • 添加事件功能
  • 标记事件功能
  • 删除事件功能

代码分享

组件代码 VuexTodoList.vue

//组件代码 VuexTodoList.vue
<template>
  <div id="app">
    <a-input placeholder="请输入任务" class="my_ipt" :value="inputValue" @change="handleInputChange" />
    <a-button type="primary" @click="addItemToList">添加事项</a-button>

    <a-list bordered :dataSource="infolist" class="dt_list">
      <a-list-item slot="renderItem" slot-scope="item">
        <!-- 复选框 -->
        <a-checkbox :checked="item.done" @change="(e) => {cbStatusChanged(e, item.id)}">{{item.info}}</a-checkbox>
        <!-- 删除链接 -->
        <a slot="actions" @click="removeItemById(item.id)">删除</a>
      </a-list-item>

      <!-- footer区域 -->
      <div slot="footer" class="footer">
        <!-- 未完成的任务个数 -->
        <span>{{unDoneLength}}条剩余</span>
        <!-- 操作按钮 -->
        <a-button-group>
          <a-button :type="viewKey === 'all' ? 'primary' : 'default'" @click="changeList('all')">全部</a-button>
          <a-button :type="viewKey === 'undone' ? 'primary' : 'default'" @click="changeList('undone')">未完成</a-button>
          <a-button :type="viewKey === 'done' ? 'primary' : 'default'" @click="changeList('done')">已完成</a-button>
        </a-button-group>
        <!-- 把已经完成的任务清空 -->
        <a @click="clean">清除已完成</a>
      </div>
    </a-list>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'app',
  data() {
    return {}
  },
  created() {
    this.$store.dispatch('getList')
  },
  computed: {
    ...mapState(['inputValue', 'viewKey']),
    ...mapGetters(['unDoneLength', 'infolist'])
  },
  methods: {
    // 监听文本框内容变化
    handleInputChange(e) {
      this.$store.commit('setInputValue', e.target.value)
    },
    // 向列表中新增 item 项
    addItemToList() {
      if (this.inputValue.trim().length <= 0) {
        return this.$message.warning('文本框内容不能为空!')
      }

      this.$store.commit('addItem')
    },
    // 很据Id删除对应的任务事项
    removeItemById(id) {
      // console.log(id)
      this.$store.commit('removeItem', id)
    },
    // 监听复选框选中状态变化的事件
    cbStatusChanged(e, id) {
      // 通过 e.target.checked 可以接受到最新的选中状态
      // console.log(e.target.checked)
      // console.log(id)
      const param = {
        id: id,
        status: e.target.checked
      }

      this.$store.commit('changeStatus', param)
    },
    // 清除已完成的任务
    clean() {
      this.$store.commit('cleanDone')
    },
    // 修改页面上展示的列表数据
    changeList(key) {
      // console.log(key)
      this.$store.commit('changeViewKey', key)
    }
  }
}
</script>

<style scoped>
#app {
  padding: 10px;
}

.my_ipt {
  width: 500px;
  margin-right: 10px;
}

.dt_list {
  width: 500px;
  margin-top: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

状态管理代码store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: 'aaa',
    // 下一个Id
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    // 为 store 中的 inputValue 赋值
    setInputValue(state, val) {
      state.inputValue = val
    },
    // 添加列表项
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    // 根据Id删除对应的任务事项
    removeItem(state, id) {
      // 根据Id查找对应项的索引
      const i = state.list.findIndex(x => x.id === id)
      // 根据索引,删除对应的元素
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 修改列表项的选中状态
    changeStatus(state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    // 清除已完成的任务
    cleanDone(state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 修改视图的关键字
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        // console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    // 统计未完成的任务的条数
    unDoneLength(state) {
      return state.list.filter(x => x.done === false).length
    },
    infolist(state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(x => !x.done)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done)
      }
      return state.list
    }
  }
})

img

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值