简介
- 注册全局指令
// Vue2.0用法
// 注册一个全局指令
// el: 指令所在的标签对象
// binding: 包含指令相关数据的容器对象
Vue.directive('upper-text', function (el, binding) {
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
})
// Vue3.0用法
const app = Vue.createApp(AttributeBindingApp1)
app.directive('upper-text',function(el,binding){
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
})
app.mount('#test1')
- 注册局部指令
directives : {
'my-directive' : {
bind (el, binding) {
el.innerHTML = binding.value.toupperCase()
}
}
}
// 注册局部指令
directives: {
'lower-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toLowerCase()
}
}
- 使用指令
v-my-directive=‘xxx’
<p v-upper-text="msg"></p>
实例: 自定义2个指令
- 功能类型于v-text, 但转换为全大写
- 功能类型于v-text, 但转换为全小写
<div id="test">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<div id="test1">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script type="text/javascript">
const AttributeBindingApp = {
data(){
return {
msg: "I Love You"
}
},
// 注册局部指令
directives: {
'lower-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toLowerCase()
}
,
'upper-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
}
}
}
Vue.createApp(AttributeBindingApp).mount('#test')
const AttributeBindingApp1 = {
data(){
return{
msg: "I Like You Too"
}
},
// 注册局部指令
directives: {
'lower-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toLowerCase()
}
}
}
// Vue3.0用法
const app = Vue.createApp(AttributeBindingApp1)
app.directive('upper-text',function(el,binding){
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
})
app.mount('#test1')