Vue之指令用法

简介

  1. 注册全局指令
 // 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')
 
  1. 注册局部指令
  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()
      }
      
      
    }
  1. 使用指令
    v-my-directive=‘xxx’
 <p v-upper-text="msg"></p>

实例: 自定义2个指令

  1. 功能类型于v-text, 但转换为全大写
  2. 功能类型于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')

Vue之指令用法

上一篇:WPF 笔记


下一篇:Android中实现一个可拖动的悬浮按钮,点击弹出菜单的功能