Introducción
1) 注册全局指令 :
Vue.directive('my-directive', function(el, binding){
el.innerHTML = binding.value.toupperCase()
})
2) 注册局部指令 :
directives: {
'my-directive'(el, binding) {
el.innerHTML = binding.value.toupperCase()
}
}
3) 使用指令 :v-my-directive='xxx'
(binding.value 就是 xxx 的值)
下列代码实现的需求:自定义两个指令:
1.功能类似于v-text,但全部都转换为大写 ---全局注册新指令
2.功能类似于v-text,但全部都转换为小写 --- 局部注册新指令
Ejemplo de código
<div id="app1">
<p v-Upper-text="msg1"></p>
<p v-Lower-text="msg1"></p>
</div>
<div id="app2">
<p v-Upper-text="msg2"></p>
<p v-Lower-text="msg2"></p>
</div>
<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
// 全局注册 新指令 v-Upper-text
// el: 指定属性所在的标签
// binding 包含指令相关信息的数据
Vue.directive("upper-text", function(el,binding){
console.log(el,binding);
el.innerHTML = binding.value.toUpperCase();
})
new Vue({
el:"#app1",
data:{
msg1:"Hello World!"
},
//局部注册新指令 v-ower-text
directives:{
'Lower-text'(el,binding){
el.innerHTML = binding.value.toLowerCase();
}
}
})
new Vue({
el:"#app2",
data:{
msg2:"Just Do It!"
}
})
</script>