Vue.directive()方法創建全局自定義指令


創建一個v-myfocus指令,實現input框自動聚焦

<body>
  <div id="app">
    <div class="add">
      編號:<input type="text" v-model="newId" v-myfocus="newId">
      品牌名稱:<input type="text" v-model="newName" @keyDown.enter="addData">
      <input type="button" value="添加" @click="addData">
    </div>

    <div class="add">
      品牌名稱:<input type="text" placeholder="請輸入搜索條件">
    </div>

    <div>
      <table class="tb">
        <tr>
          <th v-mycolor="color">編號</th>
          <th>品牌名稱</th>
          <th>創立時間</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="index">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.ctime}}</td>
          <td>
            <button @click="delData(index)" v-mycolor="color">刪除</button>
          </td>
        </tr>
        <!-- <tr>
          <td colspan="4">沒有品牌數據</td>
        </tr> -->
        <!-- 動態生成內容tr -->
      </table>
    </div>
  </div>
</body>
<script>
  // 利用Vue.directive()創建全局自定義指令,該方法有兩個參數:一個自定義指令名稱,一個是配置項(這里面主要包含一些和自定義指令執行相關的函數)
  // 1. 自定義指令名稱 不帶v-, 建議全部小寫
  Vue.directive('myfocus', {
    // bind表示這個自定義指令一綁定到dom上,就開始自動執行
    bind(el,binding) {
      console.log('bind');
    },
    // 表示dom插入到頁面上的時候自動執行
    // 這些函數都有兩個參數,一個是el(使用自定義指令的元素), 一個是binding(記錄自定義指令信息的對象)
    inserted(el, binding) {
      console.log('inserted');
      console.log(el);
      console.log(binding);
      el.focus()
    },
    // 表示自定義指令后面的值更新的時候,自動執行
    update() {
      console.log('update');
    }
  })

  // 創建一個自定義指令v-mycolor設置字體顏色
  Vue.directive('mycolor', {
    inserted(el, binding) {
      // binding.value獲取到的是傳遞到自定義指令中屬性的值
      el.style.color = binding.value
    }
  })


  let vm = new Vue({
    el: '#app',
    data: {
      color: 'red',
      newId: '', // 獲取編號框中的值
      newName: '', // 獲取品牌名稱框中的值
      list: [
        {id: 33, name: 'LV', ctime: new Date()},
        {id: 44, name: 'CC', ctime: new Date()},
        {id: 55, name: 'NIKE', ctime: new Date()},
        {id: 66, name: 'YSL', ctime: new Date()},
      ]
    },
    methods: {
      delData(idx) {
        this.list.splice(idx, 1)
      },
      addData() {
        this.list.push({id: this.newId, name: this.newName, ctime: new Date()})
        // 添加完之后,給兩個框清空
        this.newId = ''
        this.newName = ''
      }
    }
  })


</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM