vue的todolistDemo经典案例

1、用vue脚手架工具生成myproject项目

2、用webstorm软件来open打开

3、这里的/src目录下有App.vue和main.js

这里app是入口,app加载的helloworld.vue组件

4、现在我们直接从App.vue做文档

粘贴一下实现代码

App.vue

<template>
  <div id="app">
    <h1>{{title}}</h1>
    <input v-model="newItem" v-on:keyup.enter="addNewItem"/>
    <ul>
      <li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click="toggleFinish(item)">
        {{item.label}}
      </li>
    </ul>
  </div>
</template>

<script>

  import store from './store'

  export default {
    data() {
      return {
        title: 'todo list',
        items:store.fetch(),
        newItem: '',
      }
    },





    methods: {
      toggleFinish: function (item) {
        item.isFinished = !item.isFinished
      },
      addNewItem: function () {
        //添加數組
        this.items.push({
          label: this.newItem, isFinished: false
        }),
          this.newItem = ''
      }
    },
    watch:{
      //监听items
      items:{
        handler:function (items) {
          store.save(items)
        },
        deep:true
      }
    },

  }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }

  .finished {
    text-decoration: underline;
  }
</style>

说明一下,具体就是有一个点击事件来转换class,实现下划线的样式改变用到的指令是

v-on:click="toggleFinish(item)

第二个就是通过watch监听items数组来实现localstorage的存取,实现了f5重新刷新页面是,list数组仍然存在

这里的两个方法是fetch和save

代码如下:

store.js

const STORAGE_KEY = 'todos-vuejs'
//这里的常量可以随意定义,其实就是localstorage的key,val是一个[]数组
export default {
  fetch() {
    return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
    //第一次页面加载数组里面是空返回[],注意一定是windos,不是Windos,ws也不报错,一定要小心
  },
  save(items) {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
  }

}

然后在App.vue中improt store.js

import store from './store'

然后就可以直接调用了

store.fetch(), ws有提醒哟

5、最后总结一哈

这里我们使用到几个vue的常用指令和localstoeage的使用以及es6的简单调用组件,dotolist这个经典案例是vue官网的一个简单明了的案例,下一篇更加详细的说组件的使用以及组件的参数传递调用,刚接触的时候类比于iframe子父页面的传参交互,/狗头

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值