vue全解

vue进阶属性

2020-09-16  本文已影响0人  饥人谷_小霾
image.png

Directive指令

1.0自定义指令

两种写法

1.1声明一个全局指令

Vue.directive('x',directiveOptions)
自己试写当用户点击时打印一个x

Vue.directive('x', {)
      inserted: function(el) {
          el.addEventListener('click',()=>{console.log('x')})
  },//当元素被插入到页面,就监听click事件,元素是全局指令,把v-x放到哪个元素上,el就是那个元素
})

到中文文档搜索directive


image.png

属于元素绑定自定义事件


image.png

1.2声明一个局部指令

<script>//.src/components/HelloWorld.vue
export default{
  name: "HelloWorld",
directives:{
      'x': {
       inserted(el){
            el.addEventListener('click',()=>{console.log('x')})      
}    
},
},

局部指令在这里声明,只能在这个组件中用(HelloWorld.vue),组件中的组件也不行

1.3directiveOptions有哪些属性

image.png

2.0.v-on如何实现绑定事件

不用v-on的v-on

new Vue({
        directives:{
              'on2':{
                  inserted(el,info){
            el.addEventListener(info.arg,info.value)//
声明一个on2的指令,当元素被插入到页面,就监听这个元素的一个事件,对应方法是用户传的值(info.arg,info.value)
info.value就是要打印的hi
}     
}
}
})

info会展示用户信息


image.png

v-on不会只有一行代码这么简单,存在事件委托,
添加了事件监听,要记得在恰当的时间删掉,否则添加的越来越多


image.png
当从页面消失就删除

2.1指令的作用

image.png
mounted(){
    this. $el.querySelector('#h1).addEventListener('click',()=>console.log('x'))
},
beforeDestroy(){

3.0混入mixin

image.png
上一篇 下一篇

猜你喜欢

热点阅读