水一下vue官方文档传送门:https://cn.vuejs.org/v2/api/
Demo基于vue build第一个项目上修改
- 目录结构
- App.vue文件
<template> <div id="app"> <h1>{{title}}</h1> <h2 v-text="title"></h2> <h3 v-html="title"></h3> <input v-model="newItem" v-on:keyup.enter="addNew"> <ul> <li v-for="item in items" :key="item.label" v-bind:class="{finished: item.isFinished}" v-on:click="toggleFinish(item)"> {{item.label}} </li> </ul> </div> </template> <script> import Storage from './storage' // export相当于 new Vue({}); export default { // 相当于 date: function(){} 下面是ES6语法 data () { return { title: '<span>渲染HTML</span> this is a todo list', items: Storage.fetch(), newItem: '' } }, watch: { items: { handler: function (items) { Storage.save(items) }, deep: true } }, methods: { toggleFinish: function (item) { console.log(item.isFinished = !item.isFinished) }, addNew: function () { this.items.push({ label: this.newItem, isFinished: false }) console.log(this.newItem) this.newItem = '' } } } </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>
- storage.js文件
const STORAGE_KEY = 'todos-vuejs' export default { fetch: function () { return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]') }, // es6写法 save (items) { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items)) } }
- 效果图