> 文章列表 > vue-自定义指令

vue-自定义指令

vue-自定义指令

需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。

需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。

语法:

局部使用:

directives: {focus: {// 指令的定义inserted: function (el) {el.focus()}}
}

全局使用:

<script>// 注册一个全局自定义指令 `v-focus`Vue.directive('focus', {// 当被绑定的元素插入到 DOM 中时……inserted: function (el) {// 聚焦元素el.focus()}})
</script>

配置对象时常用的三个回调:

bind:指令与元素成功绑定调用

inserted:指令所在元素被插入页面时调用

update:指令所在模板结构被重新解析时使用

需求1:

  <!-- 准备好一个容器--><div id="root"><h2>当前值 <span v-text='n'></span></h2><h2>放大值 <span v-big='n'></span></h2><button @click="n++">计算</button></div><script type="text/javascript">Vue.config.productionTip = false;new Vue({el: '#root',data: {name:'尚硅谷',n:1},directives: {// big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。big (element,binding){console.log('big',this) //注意此处的this是windowconsole.log(element,binding)element.innerText = binding.value * 10},}
})</script>

并且用于指令中需要操作dom,所以其中的this是window,可以拿到元素操作

配置big指令传入参数:(element,binding)

        -element:第一个参数会拿到真实dom,可以操作真实dom

        -binding:第二个参数是binding是一个对象。name是指定的名称;expression是指定表达式,由于此时是绑定的指令n;value是指定的绑定值

需求二:

    (1)函数式:(存在问题)

  <body><!-- 准备好一个容器--><div id="root"><h2>焦点 <input v-fbind='n'></span></h2><button @click="n++">计算</button></div><script type="text/javascript">Vue.config.productionTip = false;new Vue({el: '#root',data: {name:'尚硅谷',n:1},directives: {fbind(element,binding){element.value = binding.value;element.focus()}}
})</script>

出现问题:一开始并不能获取焦点 

这种由于页面一开始解析模板,并且由于指令与数据绑定时由于element还未拿到,所以执行element.focus时,并不能生效。但是由于操作n,使数据发生改变,再次执行fbind,此时能拿到element元素

(2)对象式:(使用提供的钩子函数)

 <div id="root"><h2>焦点 <input v-fbind='n'></span></h2><button @click="n++">计算</button></div><script type="text/javascript">Vue.config.productionTip = false;new Vue({el: '#root',data: {name:'尚硅谷',n:1},directives: {fbind: {//指令与元素成功绑定时(一上来)bind (element,binding){element.value = binding.value},//指令所在元素被插入页面时inserted (element,binding){element.focus()},//指令所在的模板被重新解析时update (element,binding){element.value = binding.value}}}
})</script>