vue.js 入門案例,雙向綁定實現任務清單

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的語法
*/
相關文章
相關標籤/搜索