美文网首页
九、vue.js自定义指令

九、vue.js自定义指令

作者: 飞奔的小白 | 来源:发表于2018-02-26 16:06 被阅读0次

一、自定义指令

   分类:全局指令 , 局部指令

1.自定义全局指令

      使用全局方法Vue.directive(id,[definition])

2.自定义局部指令

      <!DOCTYPE html>
      <html lang="en">
      <head>
<meta charset="UTF-8">
<title>自定义指令</title>
<script type="text/javascript" src="js/vue.min.js"></script>
    </head>
    <body>
<div id="itany">
    <!-- <div v-hello>{{msg}}</div> -->
    <button @click="change">更新数据</button>
    <br>
    <div v-world="name">{{msg}}</div>
    <div v-wbs>111</div>
    <input type="text" v-model="msg" v-fous>
</div>
    </body>
    <script type="text/javascript">
    // 自定义全局指令
    // 注意:使用指令时必须在指令名称前面加前缀v-
Vue.directive('hello',{
    bind(){
        alert('指令第一次绑定到元素,只调用一次,可执行初始化操作');
    },
    inserted(){
        alert('被绑定元素插入到dom中调用');
    },
    update(){
        alert('被绑定元素所在模板更新时调用');
    },
    componentUpdated(){
        alert("被绑定元素所在模板完成一次周期时使用");
    },
    unbind(){
        alert('指令与元素解绑时调用,只调用一次');
    }
});
// 钩子函数的参数
Vue.directive('world',{
    bind(el,binding){
        // alert('111')
        el.style.color = 'red';
        console.log(el);
        console.log(binding);
        console.log(binding.name);//name 指令的名字
        console.log(binding.value);
    }
})
// 传入一个简单的函数
Vue.directive('wbs',function(){
    alert('aaa');
})
var vm = new Vue({
    el:'#itany',
    data:{
        msg:"hello",
        name:'alice'
    },
    methods:{
        change(){
            this.msg = "你好";
        }
    },
    directives:{
        // 自定义局部指令
        // focus:function(el){
        //  el.focus();
        // }
        focus:{
            inserted(el){
                el.focus();
            }
        }
    }
})
</script>
</html>

相关文章

网友评论

      本文标题:九、vue.js自定义指令

      本文链接:https://www.haomeiwen.com/subject/gbwhzxtx.html