vue.js 开发环境安装成功。
http://localhost:8080/ 使用vue.js双向绑定实现相似这样一个任务清单页面。
html
下面是个人学习笔记。vue
//app.vue页面 <template> <div id="app"> <h1 v-text="title"></h1> <input v-model="newItem" v-on:keyup.enter="addNew"> <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: "每 日 任 务", items: Store.fetch(), /* [ {"label":"俯卧撑10个","isFinished":true} {"label":"背单词10个","isFinished":false} ] */ newItem:'' //liclass:"thisisliclass" //赋值class名称 } }, watch:{ items:{ handler:function(items){ Store.save(items) }, deep:true } }, methods:{ toggleFinish:function(item){ item.isFinished = !item.isFinished }, addNew:function(){ this.items.push({ label: this.newItem, isFinished:false }) this.newItem='' } } } </script> <style> #app{width:400px;margin:0 auto;} .finished{text-decoration:line-through;} </style>
/*
1. export default 理解是,这是一个模块,export导出,导出的是一个对象。
2. data(){} 至关于 data:function(){},ES6语法。
data是一个函授,函数返回一个对象
3. <h1 v-text="title"></h1> 的简写方式为 <h1>{{title}}</h1> 4. v-text 和 v-html 是经常使用的数据渲染指令,text是纯文本,html会渲染html标签 5. v-for 能够渲染列表,v-for 指令须要以 item in items 形式的特殊语法 6. v-bind:class="[liclass]" 建立一个class,须要在retrun中添加liclass:"thisisliclass" ,赋值class名称 7. v-bind:class="{finished: item.isFinished}" 添加一个finished的class,建立一个对象,item.isFinished, 对应isFinished字段 若是为true就显示这个finished的class,不然就不显示 8. v-on:click="toggleFinish(item)" v-don 是事件处理器,这里添加了click事件,在 data 里面添加toggleFinish(item)函数 item.isFinished = !item.isFinishe , item.isFinished此时的值是布尔值 !item.isFinishe 是对 item.isFinished 的值进行取反,双向绑定,实现点击切换 9. v-model 在表单控件上建立双向绑定,<input> , <select> , <textarea> v-on:keyup.enter="addNew" 添加键盘事件,指定enter键值,调用addNew this.items.push 在items数组末尾添加元素 label: this.newItem 新添加的lable值和input输入的值绑定 isFinished:false 默认行为是false this.newItem='' input值输入以后,清空 10. watch 观察 Vue 实例变化的一个表达式或计算属性函数,items 指的是观察的对象 handler:function(items) 传进handler这个函数里 Store.save(items) 调用store.js里面的方法,并自动保存到 window.localStorage deep:true 设置为true,会在页面刷新时更新 isFinished 状态,不然就不会更新 Store.fetch() 调用store.js里面的方法,把存储的值给到 items
//store.js页面 const STORAGE_KEY = 'todos-vuejs' export default{ fetch(){ return JSON.parse(window.localStorage.getItem( STORAGE_KEY) || '[]') }, save (items){ window.localStorage.setItem( STORAGE_KEY,JSON.stringify(items)) } } /* 1.const 是 es6 的语法, 是不会被从新赋值的变量。 2.export default 能够理解为一套模板,导出两个方法,也是es6的语法 */