Vue 自定义指令

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width:200px;
            height:200px;
            background-color:red;
            display: flex;
            justify-content:center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div id="app">
        <h1>{{msg}}</h1>
        <p>--------------------</p>
        <h1 v-text="msg"></h1>
    </div>
    <script src="js/vue.3.2.2.js"></script>
    <script>
        //定义局部指令
        const lkDirective = {
            focus:{
                created(){
                    console.log("created");
                },
                beforeMount(){
                    console.log("beforeMount");
                },
                mounted(el) {
                    el.focus();
                },
                beforeUpdate(){
                    console.log("beforeUpdate");
                },
                updated(){
                    console.log("updated");
                },
                beforeUnmount(){
                    console.log("beforeUnmount");
                }
            }
        }

        // 1、创建Vue的实例对象
        const app = Vue.createApp({
            data(){//定义数据
                return {
                    msg:'你好!',
                    isShow:true,
                    posData:{
                        top:200,
                        left:200
                    }

                }
            },
            //挂载局部介指令
            directives:lkDirective,
            template:'<div v-show="isShow" class="box" v-fixed:pos="posData"><input type="text" placeholder="请输入" v-focus></div>'
        });
        //定义全局介指令
        // app.directive('focus',{
        //     mounted(el,{value},{transition}){
        //         el.focus();
        //     }
        // });

        app.directive('fixed',(el,binding)=>{
            // console.log(el,binding);
            el.style.position='fixed';
            el.style.left=binding.value.left+'px';
            el.style.top=binding.value.top+'px';

        })

        app.mount('#app');
    </script>
</body>
</html>

 

posted @ 2021-08-26 18:50  残星  阅读(20)  评论(0编辑  收藏  举报