Home > Web Front-end > Vue.js > How to customize instructions in Vue3? Code explanation

How to customize instructions in Vue3? Code explanation

青灯夜游
Release: 2022-07-28 19:33:45
forward
2382 people have browsed it

How to customize instructions in Vue3? The following article will teach you how to customize instructions in Vue3. I hope it will be helpful to you!

How to customize instructions in Vue3? Code explanation

The front-end of the TienChin project is Vue3. The front-end has such a requirement: some buttons on the front-end page must be displayed based on the user's permissions. If the user has the appropriate If the user has the corresponding permission, the corresponding button will be displayed; if the user does not have the corresponding permission, the button will be hidden. This is basically a requirement.

Seeing this requirement, some friends may first think of using the v-if command. This command can indeed be done. However, since the user may generally have multiple permissions, there may even be wildcards. , so this comparison is not an easy task, and a method must be written. . . Therefore, if you can use one command to implement this function, it will look much more professional.

Just do it, let’s take a look at how to customize instructions in Vue3. (Learning video sharing: vue video tutorial)

1. Result display

Let’s first take a look at the final use of custom instructions :

<button @click="btnClick" v-hasPermission="[&#39;user:delete&#39;]">删除用户</button>
Copy after login
Copy after login

Friends see that this v-hasPermission is our custom instruction. If the current user has the user:delete permission, this button will Displayed. If the current user does not have this permission, this button will not be displayed.

2. Instruction basics

First of all, I want to tell my friends that there are some differences in custom instructions between Vue2 and Vue3, which are not completely consistent. The following The introduction is mainly for the introduction of Vue3.

Let me first share with my friends how we did it, and then when I explain the code, I will talk to you about the meaning of each parameter.

2.1 Two scopes

Custom directives can define global or local scopes.

Before starting the official implementation, friends need to understand that custom instructions have two scopes, one is local custom instructions, and the other is global custom instructions. Local custom instructions can only be used in the current .vue file, while global ones can be used in all .vue files.

2.1.1 Local directives

can be defined directly in the current .vue file, as follows:

directives: {
  focus: {
    // 指令的定义
    mounted(el) {
      el.focus()
    }
  }
}
Copy after login

However, in Vue3, also You can write it like this:

<template>
    <p>
        <button v-onceClick="10000" @click="btnClick">ClickMe</button>
    </p>
</template>

<script>

    import {ref} from 'vue';

    export default {
        name: "MyVue01",
        setup() {
            const a = ref(1);
            const btnClick = () => {
                a.value++;
            }
            return {a, btnClick}
        },
        directives: {
            onceClick: {
                mounted(el, binding, vnode) {
                    el.addEventListener('click', () => {
                        if (!el.disabled) {
                            el.disabled = true;
                            setTimeout(() => {
                                el.disabled = false;
                            }, binding.value || 1000);
                        }
                    });
                }
            }
        }
    }
</script>
Copy after login

Here I have customized a command called onceClick. After adding this command to a button button, you can set how long after the button button is clicked, it will be in a disabled state to prevent users from repeating it. Click.

Friends, the execution logic of this instruction is actually very simple. el is equivalent to adding the element with this instruction and monitoring the click event of the element. If the element is clicked, the element is not in a disabled state. Then set the element to disabled, give a scheduled task, and make the element available after expiration. Brother Song will introduce the specific parameters here in detail below.

But this is only a local directive and can only be used in the current .vue file. We can also define global directives so that they can be used in all .vue files.

2.1.2 Global directives

We generally write global directives in main.js, or write a separate js file and introduce it in main.js, as follows The example is written directly in main.js:

const app = createApp(App);

app.directive('onceClick',{
    mounted(el, binding, vnode) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true;
                setTimeout(() => {
                    el.disabled = false;
                }, binding.value || 1000);
            }
        });
    }
})
Copy after login

In this way, we can use the v-onceClick command anytime and anywhere.

You may be confused about mounted and the parameters here when customizing instructions. Then Brother Song will introduce these methods and parameters to you in detail.

2.2 Seven hook functions

In Vue3, the hook functions of custom instructions mainly include the following seven types (this is quite different from Vue2):

  • created: Called before the attribute or event listener of the bound element is applied. This is useful when a directive needs to be appended to an event listener before the normal v-on event listener is called.
  • beforeMount: Called when the directive is bound to the element for the first time and before the parent component is mounted.
  • mounted: Called after the parent component of the bound element is mounted, Most of the custom instructions are written here.
  • beforeUpdate: Called before updating the VNode containing the component.
  • updated: Called after the containing component's VNode and the VNodes of its subcomponents are updated.
  • beforeUnmount: Called before unmounting the parent component of the bound element
  • unmounted: Called only once when the directive is unbound from the element and the parent component has been unmounted.

Although there are many hook functions, which may seem a bit intimidating, the most commonly used function in our daily development is actually the mounted function.

2.3 四个参数

这里七个钩子函数,钩子函数中有回调参数,回调参数有四个,含义基本上和 Vue2 一致:

  • el:指令所绑定的元素,可以用来直接操作 DOM,我们松哥说想实现一个可以自动判断组件显示还是隐藏的指令,那么就可以通过 el 对象来操作 DOM 节点,进而实现组件的隐藏。
  • binding:我们通过自定义指令传递的各种参数,主要存在于这个对象中,该对象属性较多,如下属性是我们日常开发使用较多的几个:

    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-hasPermission="['user:delete']" 中,绑定值为 'user:delete',不过需要小伙伴们注意的是,这个绑定值可以是数组也可以是普通对象,关键是看你具体绑定的是什么,在 2.1 小节的案例中,我们的 value 就是一个数字。
    • expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
    • arg:传给指令的参数,可选。例如 v-hasPermission:[name]="'zhangsan'" 中,参数为 "name"。
  • vnode:Vue 编译生成的虚拟节点。
  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

除了 el 之外,其它参数都应该是只读的,切勿进行修改。如果需要在钩子之间共享数据,建议通过元素的 dataset 来进行。

2.4 动态参数

有一种动态参数,这里也和小伙伴们分享下。正常情况下,我们自定义指令时传递的参数都是通过 binding.value 来获取到的,不过在这之外还有一种方式就是通过 binding.arg 获取参数。

我举一个简单例子,假设我们上面这个 onceClick 指令,默认的时间单位时毫秒,假设现在想给时间设置单位,那么我们就可以这样写:

const app = createApp(App);

app.directive('onceClick',{
    mounted(el, binding, vnode) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true;
                let time = binding.value;
                if (binding.arg == "s") {
                    time = time * 1000;
                }
                setTimeout(() => {
                    el.disabled = false;
                }, time);
            }
        });
    }
})
Copy after login

在自定义指令的时候,获取到 binding.arg 的值,这样就可以知道时间单位了,在使用该指令的时候,方式如下:

<button v-onceClick:[timeUnit]="10" @click="btnClick">ClickMe</button>
<script>

    import {ref} from 'vue';

    export default {
        name: "MyVue01",
        setup() {
            const timeUnit = ref('s');
            return {timeUnit}
        }
    }
</script>
Copy after login

timeUnit 是一个提前定义好的变量。

3. 自定义权限指令

好啦,有了上面的基础知识,接下来就来看我们本文的主题,自定义权限指令,我写一个简单的例子大家来看下:

const usersPermissions = ['user'];

app.directive('hasPermission', {
    mounted(el, binding, vnode) {
        const {value} = binding;
        let f = usersPermissions.some(p => {
            return p.indexOf(value) !== -1;
        });
        if (!f) {
            el.parentNode && el.parentNode.removeChild(el);
        }
    }
})
Copy after login

usersPermissions 表示当前用户所具备的权限,正常该数据应该是从服务端加载而来,但是我这里简单起见,就直接定义好了。

具体的逻辑很简单,先从 binding 中提取出 value 的值,这就是当前控件所需要的权限,然后遍历 usersPermissions 用一个 some 函数,去查看 usersPermissions 中是否有满足条件的值,如果没有,说明当前用户不具备展示该组件所需要的权限,那么就要隐藏这个组件,隐藏的方式就是获取到当前组件的父组件,然后从父组件中移除当前组件即可。

这是一个全局的指令,定义好之后,我们就可以在组件中直接使用了:

<button @click="btnClick" v-hasPermission="[&#39;user:delete&#39;]">删除用户</button>
Copy after login
Copy after login

好啦,Vue3 自定义组件学会了没?松哥在最近的 TienChin 项目视频中也会和大家分享这块的内容,敬请期待。

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of How to customize instructions in Vue3? Code explanation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template