VUE:內建指令與自定義指令
阿新 • • 發佈:2018-11-15
VUE:內建指令與自定義指令
常用的內建指令
1)v:text 更新元素的 textContent
2)v-html 更新元素的 innerHTML
3)v-if 如果為true,當前標籤才會輸出到頁面
4)v-else 如果為false,當前標籤才會輸出到頁面
5)v-show 通過控制display樣式來控制顯示/隱藏
6)v-for 遍歷陣列/物件
7)v-on 繫結事件監聽,一般簡寫為@
8)v-bind 強制繫結解析表示式,可以省略v-bind
9)v-model 雙向資料繫結
10)ref 指定唯一標識,vue物件通過$els屬性訪問這個元素物件
11)v-cloak 防止閃現,與css配合:[v-cloak]{display:none}
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> [v-cloak]{ display: none; } </style> </head> <body> <div id="example"> <p ref="content">taosir is learning...</p> <button @click="hint">提示</button> <!--<p v-text="msg"></p>--> <p v-cloak>{{msg}}</p> </div> <script type="text/javascript" src="../js/vue.js" ></script> <script> alert('----') new Vue({ el:'#example', data:{ msg:'濤先森正在努力學習' }, methods:{ hint(){ alert(this.$refs.content.innerHTML); } } }) </script> </body> </html>
自定義指令
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <!-- 1.註冊全域性指令 Vue.directive('my-directive',function(el,binding){ el.innerHTML = binding.value.toupperCase() }) 2.註冊區域性指令 directives: 'my-directive':{ bind(el,binding){ el.innerHTML = binding.value.toupperCase() } } 3.使用指令 v-my-directive='xxx' --> <!-- 需求:自定義2個指令 1.功能類似於 v-text,但是轉換為全大寫 2.功能類似於 v-text,但是轉換為全小寫 --> <div id="test1"> <p v-upper-text="msg1"></p> <p v-lower-text="msg1"></p> </div> <div id="test2"> <p v-upper-text="msg2"></p> <p v-lower-text="msg2"></p> </div> <script type="text/javascript" src="../js/vue.js" ></script> <script> //定義全域性指令 //el:指令屬性所在的標籤物件 //binding:包含指令相關資訊資料的物件 Vue.directive('upper-text',function(el,binding){ console.log(el,binding); el.textContent = binding.value.toUpperCase() }) new Vue({ el:'#test1', data:{ msg1:'taosir love java!' }, //註冊區域性指令 directives:{ 'lower-text'(el,binding){ el.textContent = binding.value.toLowerCase() } } }) new Vue({ el:'#test2', data:{ msg2:'taosir love Vue!' } }) </script> </body> </html>