相思资源网 Design By www.200059.com

一个简单的vuex应用的小例子,一段自己的学习记录。

todolist就是一个简单的输入框,一个按钮,一个文本显示区域,可以逐条进行删除。

1.在用vue-cli生成好的HelloWorld.vue文件中直接写代码,先删除所有的自带代码

<template>
 <div class="hello">
  <input type="text">
  <button>增加事项</button>
  <ul>
   <li>item</li>
  </ul>
 </div>
</template>

要把`input`中的值在经过`button`点击后,显示在`li`中,`input`有`v-model`属性进行值的绑定,

让`li`的数据是一个数组。相当于在数组中push input的值。

2.在src目录下,新建一个store文件夹,创建一个index.js文件

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

Vue.use(Vuex)

const store = new Vuex.Store({
 state: {
  inputVal: 'lily',
  list: ['1', '2', '3']
 },
 mutations: {
  changeListValue(state, inputVal) {
   state.list.push(inputVal)
   state.inputVal = ''
  },
  handleDel(state, idx) {
   state.list.splice(idx, 1)
  }
 },
 actions: {
  changeListValue: ({commit}, inputVal) => {
   return commit('changeListValue', inputVal)
  },
  handleDel: ({commit}, idx) => {
   return commit('handleDel', idx)
  }
 }
})
export default store

3.回到HelloWorld.vue

<template>
 <div class="hello">
  <input v-model="$store.state.inputVal" type="text">
  <button @click="changeListValue(inputVal)">增加事项</button>
  <ul v-for="(item, idx) in list">
   <li @click="handleDel(idx)">{{item}}</li>
  </ul>
 </div>
</template>

<script>
 import {mapState, mapActions} from 'vuex'
 export default {
  name: 'HelloWorld',
  computed: {
   ...mapState(['list', 'inputVal'])
  },
  methods: {
   ...mapActions(['changeListValue', 'handleDel'])
  }
 }
</script>

4.完成以后,有个困扰就是在input的v-model中写inputVal会报错,请大神帮我解答下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
vuex,todolist

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“详解vuex的简单todolist例子”

暂无详解vuex的简单todolist例子的评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。