如何将json数据通过vuex渲染到页面上

1,014 阅读2分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

如何将json数据通过vuex渲染到页面上

  • 在store中导入axios
import axios from 'axios'
  • actions中执行异步操作,来将json数据拿到store中
actions: {
    getList(context) {
      axios.get('./list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  • 通过mutation将数据送到state中去
state: {
    // 所有的任务列表
    list: []
  },
  mutations: {
    initList(state, list) {
      state.list = list
    }
  },
  • 在app.vue中按需导入
import { mapState } from 'vuex'
  • 在页面加载时通过action获取数据
created() {
    this.$store.dispatch('getList')
  },
  • 通过计算属性的方式将state中的list内容放到app.vue中
computed: {
    ...mapState(['list'])
  }
  • 完成数据替换

如何使文本框输入内容后同步

  • 给state设置一个文本的存储
state: {
    // 文本框中的内容
    inputValue: 'aaa'
  },
  • 属性绑定state的inputValue + 判断当文本框内容发生改变时,触发函数
<a-input
      :value="inputValue"
      @change="handleInputChange"
    />
          
computed: {
    ...mapState(['list', 'inputValue'])
  },
  • 通过函数来监听最新文本并通过mutation更新state数据
handleInputChange(e) {
      console.log(e.target.value)
      this.$store.commit('setInputValue', e.target.value)
}


mutations: {
    setInputValue(state, val) {
      state.inputValue = val
    }
  },
  • 完成

如何完成添加按钮

  • 绑定click事件
  • 新增mutation函数用于执行操作
state: {
    // 下一个Id
    nextId: 5
  },
mutations: {
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    }
  },
  • 调用
addItemToList() {
      if (this.inputValue.trim().length <= 0) {
        return this.$message.warning('文本框内容不能为空')
      }

      this.$store.commit('addItem')
    }
  • 完成

如何删除一条数据

  • 为删除按钮添加click事件,参数为当前数据的id
<a-list-item slot="renderItem" slot-scope="item">
        <a slot="actions" @click="removeItemById(item.id)">删除</a>
</a-list-item>
  • 在mutation中写入删除函数
    • 寻找索引:当前索引是否等于当前id
    • 删除:元素,一个
removeItem(state, id) {
      // 根据Id查找对应项的索引
      const i = state.list.findIndex(x => x.id === id)
      // 根据索引,删除对应的元素
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    }

复选框默认状态绑定

  • 利用属性绑定使checked为true或者为false来进行同步
<a-checkbox :checked="item.done">{{ item.info }}</a-checkbox>

复选框选中与取消

  • 为复选框绑定change事件
<a-checkbox
          :checked="item.done"
          @change="(e) => {cdstatusChanged(e, item.id)}"
          >{{ item.info }}</a-checkbox>
  • 在函数中拿到id和当前复选框的选中状态
cdstatusChanged(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)
    }
  • 在mutation函数中将state的选中状态改变
// 修改列表项的选中状态
    changeStatus(state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    }

清除已完成任务

  • 绑定单击事件并初始化函数
<a @click="clean">清除已完成</a>
// 清除已完成的任务
    clean() {
      this.$store.commit('cleanDone')
    }
  • mutation中写入删除逻辑
    • filter可以将结果返回为一个新数组
    • 将所有done=false的结果变为一个数组并将原来的state.list代替
// 清除已完成的任务
    cleanDone(state) {
      state.list = state.list.filter(x => x.done === false)
    }

按钮的高亮效果切换

  • 为要高亮的按钮绑定单击事件,并为每个事件设置不同的字符串
<a-button @click="changeList('all')" >全部</a-button>
<a-button @click="changeList('undone')" >未完成</a-button>
<a-button @click="changeList('done')" >已完成</a-button>
  • 初始化单击函数
// 修改页面上展示的列表数据
    changeList(key) {
      console.log(key)
      this.$store.commit('changeViewKey', key)
    }
  • 向state中新增viewKey用来存储高亮显示的按钮并通过mutation来完成viewKey的切换
state: {
    viewKey: 'all'
  },
  mutations: {
    // 修改视图关键字
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  • 用外部引入的方式将viewKey搞到app.vue上
    ...mapState(['list', 'inputValue', 'viewKey']),
  • 当viewKey = 当前按钮的字符串时,type值变为primary,否则变为default,记住要属性绑定
<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
          >

点击按钮切换状态条数

  • 因为数据源一直是list所以点按钮没有用
  • 所以只需要让list能够动态变化就可以了
  • 在getter中新增函数
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
    }
  • 将state的list删除,取而代之的是新的Getters变化的list
<a-list bordered :dataSource="infolist" class="dt_list">


computed: {
    ...mapState(['inputValue', 'viewKey']),
    ...mapGetters(['unDoneLength', 'infolist'])
  },