前端與移動開發之vue-day1(5)
阿新 • • 發佈:2018-11-20
自定義指令
自定義全域性和區域性的 自定義指令:
// 自定義全域性指令 v-focus,為繫結的元素自動獲取焦點: Vue.directive('focus', { inserted: function (el) { // inserted 表示被繫結元素插入父節點時呼叫 el.focus(); } }); // 自定義區域性指令 v-color 和 v-font-weight,為繫結的元素設定指定的字型顏色 和 字型粗細: directives: { color: { // 為元素設定指定的字型顏色 bind(el, binding) { el.style.color = binding.value; } }, 'font-weight': function (el, binding2) { // 自定義指令的簡寫形式,等同於定義了 bind 和 update 兩個鉤子函式 el.style.fontWeight = binding2.value; } } 自定義指令的使用方式: <input type="text" v-model="searchName" v-focus v-color="'red'" v-font-weight="900"> Vue 1.x 中 自定義元素指令【已廢棄,瞭解即可】 Vue.elementDirective('red-color', { bind: function () { this.el.style.color = 'red'; } }); 使用方式: <red-color>1232</red-color>