感受2.0好坑啊,自定義指令和1.0徹底不同,而且文檔寫得也不太清晰,下面是我寫得一個demo,但願幫助你們更好地理解自定義指令javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <!-- <script type="text/javascript" src="vue.js"></script> --> </head> <body> <div id="box"> <p v-demo="{color:'red'}">紅色文字</p> <input type="text" name="" v-focus> </div> <script type="text/javascript"> window.onload = function() { // 全局指令 Vue.directive('demo',{ bind:function(el,val){ el.style.color = val.value.color } }); Vue.directive('focus',{ inserted: function(el,val) { el.focus() } }); // 局部指令 var app = new Vue({ el: '#box', directives: { demo: { bind: function(el, val) { el.style.color = val.value.color } }, focus: { inserted: function(el,val) { el.focus() } } } }); } </script> </body> </html>