感觉2.0好坑啊,自定义指令和1.0完全不一样,并且文档写得也不太清晰,下面是我写得一个demo,希望帮助大家更好地理解自定义指令
<!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>