Vue的學習之路十六:自定義私有指令

var vm = new Vue({
  el: '#app',
  data: {
    id: '',
    name: '',
    keywords: '',
    list: [
      { id: 1, name: '奔馳', ctime: new Date() },
      { id: 2, name: '寶馬', ctime: new Date() },
    ],
  },
  methods: {
    add() {
      // 添加的方法
      // 分析
      // 1. 獲取到 id 和 name,直接從 data 上面獲取
      // 2. 組織出一個對象
      // 3. 把這個對象,調用數組的相關方法,添加到當前data上的list中
      // 4. 在Vue中,已經實現了數據的雙向綁定,每當我們修改了data中的數據,Vue會默認監聽到數據的改動,自動把最新的數據,應用到頁面上
      // 5. 更多的是在進行 VM 中 Model 數據的操作,同時在操作 Mode 數據的時候,指定的業務邏輯操作
      if (this.id == '' || this.name == '') return
      this.list.push({ id: this.id, name: this.name, ctime: new Date() })
      this.id = this.name = ''
    },
    del(id) {
      // 根據id刪除數據
      // 分析
      // 1. 如何根據 id 找到要刪除對象的索引
      // 2. 如果找到索引了,直接調用 數組的 splice 方法

      // this.list.some((item, i) =>{
      //   if (item.id == id){
      //     this.list.splice(i, 1)
      //     // 在數組的 some 方法中,如果 return true,就會立即終止這個數組的後續循環
      //     return true;
      //   }
      // })

      var index = this.list.findIndex((item) => {
        if (item.id == id) {
          return true
        }
      })
      this.list.splice(index, 1)
    },
    search(keywords) {
      // 根據關鍵字進行搜索
      // var newList = []
      // this.list.forEach(item => {
      //   if (item.name.indexOf(keywords) != -1) {
      //     newList.push(item);
      //   }
      // })
      // return newList

      // 注意:forEach some filter findIndex 這些都屬於數組的新方法,都會對數組中的每一項,進行遍歷執行相關的操作
      return this.list.filter(item => {
        // if(item.name.indexOf(keywords) != -1)

        // 注意:ES6中,爲字符串提供了一個新方法叫做,String.prototype.includes('要包含的字符串')
        // 如果包含,則返回 true,否則返回 false
        if(item.name.includes(keywords)){
          return item
        }
      })
    },
  },
  directives: {
    'fontweight': {
      bind: function(el, binding){
        el.style.fontWeight = binding.value
      },
     'fontsize': function(el, binding){ // 注意,這個function 等於把代碼寫到了 bind 和 update 中去
         el.style.fontSize = parseInt(binding.value) +'px'
       }
    }
  }
})
  1. 在Vue實例中使用 directives屬性,定義私有指令
  2. 簡寫函數,等於把代碼寫到了 bindupdate 中去
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章