前端二次封装组件vue

(一)Vue.directive指令(自定义指令)

2018-02-14  本文已影响0人  我拥抱着我的未来

本节知识点

全局api概述

Vue.directive 指令

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
   <div id="app">
       <span>{{message}}</span>
       <button @click="add"> 点击开始加1</button>
   </div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:10,
            color: "green"
        },
        methods:{
            add:function(){
                this.message++;
            }
        }
    })
</script>
</html>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
   <div id="app">
       <span v-hello="color3">{{message}}</span>
       <button @click="add"> 点击开始加1</button>
   </div>
</body>
<script>
    Vue.directive("hello",function(el,binding,vnode){
       el.style["color"]= binding.value;
    })
    var app = new Vue({
        el:"#app",
        data:{
            message:10,
            color3:"red"
        },
        methods:{
            add:function(){
                this.message++;
            }
        }
    })
</script>
</html>

自定义指令的生命周期

自定义指令有5个生命周期(也叫作钩子函数)分别是bind ,inserted,update,componentUpdate,unbind

function unbind(){
  app.$destroy()
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
   <div id="app">
       <span v-hello="color3">{{message}}</span>
       <button @click="add"> 点击开始加1</button>
       <button onclick="jiebang()">解绑</button>
   </div>
</body>
<script>
    function jiebang(){
        app.$destroy();
    }
    Vue.directive("hello",{
        bind:function(el,bingind,vnode){
            el.style["color"] = bingind.value;
            console.log("1-bind");
        },
        inserted:function(){
            console.log("2-insert");
        },
        update:function(){
            console.log("3-update");
        },
        componentUpdated:function(){
            console.log('4 - componentUpdated');
        },
        unbind:function(){
            console.log('5 - unbind');
        }
    })
    var app = new Vue({
        el:"#app",
        data:{
            message:10,
            color3:"red"
        },
        methods:{
            add:function(){
                this.message++;
            }
        }
    })
</script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读