VUE3之其它组件

自定义指令

基本使用

局部指令如同局部组件需要在App内部使用directives option,directives是一个对象,里面定义了一些自定义的指令(缺省v-):

<script>
    export default {
        // 局部指令
        directives:{
            focus:{
                mounted(el,bindings,vnode,preVnode) {
                    console.log("focus mounted");
                    el.focus();
                },
            }
        }
    }
</script>

全局指令如同全局组件,需要调用App的directive方法来注册:

const app=createApp(App);

app.directive("focus",{
    mounted(el,bindings,vnode,preVnode) {
        console.log("focus mounted");
        el.focus();
    },
});
app.mount('#app')

生命周期函数

生命周期函数中传来四个参数:1.element:当前的元素;2.bindings:传入的修饰符、值等;3.vnode;4.前一个vnode:

        directives:{
            sk:{
                created(el,bindings,vnode,preVnode) {
                    console.log("sk created",el,bindings,vnode,preVnode);
                },
                beforeMount() {
                    console.log("sk beforeMount");
                },
                mounted() {
                    console.log("sk mounted");
                },
                beforeUpdate() {
                    console.log("sk beforeUpdate");
                },
                updated() {
                    console.log("sk updated");
                },
                beforeUnmount() {
                    console.log("sk beforeUnMount");
                },
                unmounted() {
                    console.log("sk unmounted");
                },
            }
        },

对自定义指令添加修饰符和值,可以在bindings中接收到:

<template>
    <div>
        <button v-if="counter<2" v-sk.aaa.bbbb="'123'" @click="increment">当前计数:{{counter}}</button>
    </div>
</template>
bbibinbib

bindings使用方式:

                created(el,bindings,vnode,preVnode) {
                    console.log("sk created",el,bindings,vnode,preVnode);
                    console.log(bindings.value);
                    console.log(bindings.modifiers);
                },

时间格式化的练习:

// format-time.js
import dayjs from "dayjs"

export default function(app){
    let formatString="YYYY-MM-DD HH:mm";
    app.directive("format-time",{
        created(el,bindings) {
            if (bindings.value){
                formatString=bindings.value;
            }
        },
        mounted(el,bindings) {
            const textContent = el .textContent;
            let timestamp = parseInt(textContent);
            if (textContent.length===10){
                timestamp*=1000;
            }
            el.textContent=dayjs(timestamp).format(formatString);
        },
    })
}


// App.vue
<template>
    <div>
        <h2 v-format-time="'YYYY-MM-DD'">{{timestamp}}</h2>
    </div>
</template>

通过函数注册到App中:

// directives/index.js
import registerFormat from "./format-time";
export default function registerDirectives(app){
    registerFormat(app)
}

// main.js
registerDirectives(app);

发表评论