vuex从入门到实战多功能TodoList

1.vuex的核心盖概念

在这里插入图片描述
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。他可以方便实现组件之间的数据共享
在这里插入图片描述

1.1 state

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

  • 组件中访问state第一种方式:

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

  • 组件中访问state第二种方式:

1.从vuex中按需求导入mapState函数
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
2. 将全局数据,映射为当前组件的计算属性
computed :{ ...mapState(['count']) }

1.2 mutation

mutation用于变更store中的数据
①只能通过mutation更Store数据,不可以直接操作Store中的数据。
②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

  1. this.$store.commit()是触发mutations的第一种方式,
//store.js中定义mutations
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
   add(state) {
   //更改状态
    state.count++
   }
  }
})
//组件中接收触犯mutations
methods: {
    add() {
      this.$store.commit('add')
    },

  },



//mutations可以传递参数
 mutations: {
   add2(state,step) {
    state.count += step
   }
  }
//触发带参数的mutation
methods: {
    add() {
      this.$store.commit('add',3)
    },

  },
  1. 触发mutations的第二种方式:通过以函数映射的方式

1.从vuex中按需求导入mapState函数
import {mapMutations} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
2. 将指定的mutations函数,映射为当前组件的methods函数
methods:{ ...mapMutations(['add']) }

1.3 action

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

  1. this.$store.dispatch是触发actions的第一 种方式
//定义store.js 中定义action
  actions: {
    addAsync(context) {
      setTimeout(()=> {
        context.commit('add')
      },1000)
    }
  }


//在事件方法中通过dispatch触发action
add () {
    //  触发action
    this.$store.dispatch('addAsync')
  }


触发异步任务携带参数

  mutations: {
   add(state,step) {
    state.count += step
   }
  },
  actions: {
    addAsync(context,step) {
      setTimeout(()=> {
        context.commit('add',step)
      },1000)
    }
  }
//触发action
add () {
    this.$store.dispatch('addAsync',5)
  }
  1. 触发actions的第二 种方式:通过以函数映射的方式

1.从vuex中按需求导入mapState函数
import {maptActions} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
2. 将指定的mutations函数,映射为当前组件的methods函数
methods:{ ...maptActions(['addAsync']) }

1.4 getter

Getter于对Store中的数据进行加工处理形成新的数据。他不会修改state中的原始数据起到的是包装数据的作用
①Getter 可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
②Store 中数据发生变化,Getter 的数据也会跟着变化。

  1. this.$store.getters.名字是的调用getters第一 种方式
//组件中调用
 {{$store.getters.showNum}}
 //store.js中定义
   getters: {
    showNum (state){
      return `当前最新的数据${state.count}`
    }
  }
  1. 通过以函数映射的方式

1.从vuex中按需求导入mapState函数
import {maptGetters} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
2. 将指定的mutations函数,映射为当前组件的methods函数
computed :{ ...maptGetters(['showNum']) }

2.用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
    }
  }
})

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值