Vuex从入门到实战(十四)——【实践篇】完结撒花!!!

news/2024/7/9 23:49:38 标签: vue, vuex, getters

Todos 11

这节实现点击三个按钮显示出相应的列表,使用 getters 实现,因为他不会改变我们的原始数据。

完整代码地址:https://github.com/huijieya/vuex_demo在这里插入图片描述

1、store/index.js——getters 增加 infoList ,根据 viewkey 返回列表真正用的数据

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '', // 文本框内容
    nextId: 5, // list中id属性取值
    viewKey: 'all' // 当前选中按钮
  },
  mutations: {
    initList (state, step) {
      state.list = step
    },
    // 为 inputValue 赋值
    setInputValue (state, val) {
      state.inputValue = val
    },
    // 将inputValue存储到list中
    addInputValue (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++

      state.inputValue = ''
    },
    removeItem1 (state, step) {
      state.list.forEach((e, index) => {
        if (e.id === step) {
          return state.list.splice(index, 1)
        }
      })
    },
    removeItem2 (state, step) {
      // 根据id查找对应的索引
      const i = state.list.findIndex(x => x.id === step)
      // 根据索引,删除对应的元素
      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.done
      }
    },
    // 清除已完成列表项
    listClean (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 修改视图的关键字
    changeViewKey (state, step) {
      state.viewKey = step
    }
  },
  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
    },
    // 根据key返回相应list
    infoList (state) {
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done)
      } else if (state.viewKey === 'unDone') {
        return state.list.filter(x => !x.done)
      }
      return state.list
    }
  }
})

2、App.vue——mapGetters 引入刚写的 infoList ,更改 :dataSource 的绑定,之前的 list 已经没用了,可以删掉。

<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='onChange($event, 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="cleanDone()">清除已完成</a>
      </div>
    </a-list>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  name: 'app',
  data () {
    return {
      data: []
    }
  },
  created () {
    this.$store.dispatch('getList')
  },
  computed: {
    ...mapState(['inputValue', 'viewKey']),
    ...mapGetters(['infoList', 'unDoneLength', 'unDoneList', 'doneList'])
  },
  methods: {
    ...mapMutations(['setInputValue', 'addInputValue', 'removeItem1', 'removeItem2', 'changeStatus', 'listClean', 'changeViewKey']),
    // 监听文本框内容变化
    handleInputChange (e) {
      // 拿到最新值,并同步到store
      console.log(e.target.value)
      this.setInputValue(e.target.value)
    },
    // 向列表项中新增 item 项
    addItemToList () {
      if (this.inputValue.trim().length <= 0) { // 判空处理
        return this.$message.warning('文本框内容不能为空')
      }
      this.addInputValue()
    },
    removeItemById (id) {
      this.removeItem1(id)
    },
    // 监听复选框选中状态的变化
    onChange (e, id) {
      // 通过 e.target.checked 可以接受到最新的选中状态
      const param = {
        id: id,
        done: e.target.checked
      }
      this.changeStatus(param)
      // 另一种写法:
      // @change='(e) => {onChange(e, item.id)}'
      // console.log(`checked = ${e.target.checked}`)
    },
    // 清除已完成绑定事件
    cleanDone () {
      this.listClean()
    },
    // 修改页面中展示的列表项
    changeList (key) {
      this.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>

完结


http://www.niftyadmin.cn/n/1486139.html

相关文章

兼容性超好的CSS滑动门

代码简介&#xff1a;兼容性好的CSS没去门&#xff0c;其实这里还是要用到JS来配合&#xff0c;不过相对其它的滑动门菜单&#xff0c;本没去门将代码做到了最简化&#xff0c;而且兼容性也不错&#xff0c;因此这是本菜单的亮点&#xff0c;从外观上来说&#xff0c;它和其它的…

PowerShell 异常处理

在使用 PowerShell 的过程中&#xff0c;发现它的异常处理并不像想象中的那么直观&#xff0c;所以在这里总结一下。 Terminating Errors 通过 ThrowTerminatingError 触发的错误称为 Terminating Errors。本质上它是创建了一个异常&#xff0c;所以我们可以使用 catch 语句来捕…

js对象与字符串相互转换<JSON.stringify, JSON.parse>

【对象转为字符串】 const obj {id: 0,name: 张三,age: 12 } const objToStr JSON.stringify(obj) console.log(obj:, obj) console.log(objToStr:, objToStr)【 json字符串转为对象】 const str {"id":0,"name":"张三","age":12…

Spring中Model,ModelMap以及ModelAndView之间的区别

原文链接&#xff1a;http://blog.csdn.net/zhangxing52077/article/details/75193948 Spring中Model,ModelMap以及ModelAndView之间的区别 标签&#xff1a; modelMapmodelModelAndView2017-07-15 21:54 1771人阅读 评论(0) 收藏 举报分类&#xff1a;springmvc&#xff08;14…

前端项目里常见的十种报错及其解决办法

错误一&#xff1a;Uncaught TypeError: Cannot set property onclick of null at operate.js:86图片.png原因&#xff1a; 当js文件放在head里面时&#xff0c;如果绑定了onclick事件&#xff0c;就会出现这样的错误&#xff0c;是因为W3School的写法是浏览器先加载完按钮节点…

SugarCRM 主表EditView.php 中添加子表明细Items 并一同保存

1.在主表模块中创建子表字段标签 /wwws/language/zh_cn.lang.php LBL_ConsignmentItem>提运单明细, LBL_ADDROW>新增明细, LBL_REMOVEROW>删除, LBL_SequenceNumeric > 托运货物序号, LBL_MarksNumbers > 唛头, LBL_CargoDescription >…

【echarts报错】Component series.line not exists. Load it firsrt和Cannot read property ‘init‘ of undefined

【折线图堆叠示例效果】 【echarts版本升级之后正确写法】 <!-- html --> <a-card-grid style"width:70%;height:611px;text-align:center"><div id"lineChart" :style"{ width: 600px, height: 500px, padding: 30px }">&…

三. Python基础(3)--语法

三. Python基础(3)--语法 1. 字符串格式化的知识补充 tpl "我是%s,年龄%d,学习进度100%" %(Arroz,18) print(tpl) # 会提示&#xff1a;ValueError: incomplete format# 占位符只有格式化时才有意义 msg "我是%s,年龄%d,学习进度100%" print(msg) # 结…