Home  >  Article  >  Web Front-end  >  Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

WBOY
WBOYforward
2022-01-30 06:00:314390browse

This article brings you relevant knowledge about Vue instructions and manual encapsulation of custom instructions. I hope it will be helpful to you.

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

In the front-end basic interview, Vue’s instructions are considered a high-frequency interview question

The interviewer asked: What instructions does Vue have?

Just tell him: As of Vue3.2, Vue has a total of 16 built-in instructions, including:

v-text, v-html, v-show, v-if , v-else, v-else-if, v-for, v-on, v-bind, v-model, v-slot, v-pre, v-cloak, v-once, v-memo, v-is , among which v-memo is new in 3.2, v-is is abandoned in 3.1.0

If the interviewer further asks: How to encapsulate a custom instruction?

Just tell him: Custom instructions are divided into global custom instructions and local instructions; in Vue3, you can register a global custom instruction through directive() on the application instance. If you want to register a local instruction, you can Configure the directives option in the component to register local instructions

After reading this article, you will fully understand the 16 Vue instructions and master how to customize a directive

1. Introduction

1.1 What is a Vue directive

In Vue, a directive is actually a special attribute

Vue will do something behind the scenes based on the directive. As for what to do specifically, Vue will perform different operations according to different instructions. The details will be discussed later

1.2 What are the characteristics

Vue An obvious feature of instructions is that they all start with v-, for example: v-text

<span v-text="msg"></span>

2. Built-in instructions

2.1 What are the built-in instructions in Vue?

Built-in instructions refer to Vue’s own instructions, which can be used out of the box.

Vue has a total of 16 built-in instructions, including:

v-text, v-html, v-show, v-if, v-else, v-else-if, v-for, v-on, v-bind, v-model, v-slot, v-pre, v-cloak, v-once, v-memo, v-is, among which v-memo is new in 3.2, v-is is abandoned in 3.1.0

Let’s take a look at these built-in instructions Basic usage

2.2 Understand the basic usage of the 16 built-in instructions

2.2.1 v-text

v-text is used to update the textContent of the element, for example:

<h1 v-text="msg"></h1>

The content of the h1 element ultimately depends on the value of msg

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

2.2.2 v-html

is very similar to v-text, except that v-html is used to update the innerHTML of the element, such as

<div v-html="&#39;<h1>Hello LBJ</h1>&#39;"></div>

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

It should be noted that the content inside must be inserted as ordinary HTML

2.2.3 v-show

v-show can be based on the true value of the expression. False value, switches the display value of the element, used to control the display and hiding of the element, for example:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

It can be seen that when the conditions change, this instruction triggers display or hiding Transition effects

Note: v-show does not support the

2.2.4 v-if

v-if is used to conditionally render elements based on the true or false value of an expression.

Compared with v-show, v-if is the destruction or reconstruction of elements when switching, rather than simply Show and hide

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

You can see that when the expression is false, v-if directly destroys the element, while v-show only hides it visually

And v-if can be

2.2.5 v-else

v-else does not require an expression, which means adding an "else block", which is equivalent to displaying the elements of v-if when v-if meets the condition, otherwise displaying the elements of v-else, for example:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

Note: The sibling element before v-else must have v-if or v-else-if

2.2.6 v-else-if

Similarly, the "else if block" representing v-if is the same as v-else. The previous sibling element must have v-if or v-else-if, for example:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

2.2.7 v-for

v-for is a directive for iteration, which can render elements or template blocks multiple times based on source data, for example:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

You can also specify an alias for the array index or the key used for the object

<div v-for="(item, index) in items"></div>
<div v-for="(value, key) in object"></div>
<div v-for="(value, name, index) in object"></div>

2.2.8 v-on

v-on is used to bind events to elements, which can be abbreviated as: @

Modifier

  • .stop - Call event.stopPropagation()

  • .prevent - 调用 event.preventDefault()

  • .capture - 添加事件侦听器时使用 capture 模式

  • .self - 只当事件是从侦听器绑定的元素本身触发时才触发回调

  • .{keyAlias} - 仅当事件是从特定键触发时才触发回调

  • .once - 只触发一次回调

  • .left - 只当点击鼠标左键时触发

  • .right - 只当点击鼠标右键时触发

  • .middle - 只当点击鼠标中键时触发

  • .passive - { passive: true } 模式添加侦听器

例如:

<!-- 停止冒泡 -->
<button @click.stop="doThis"></button>

需要注意,用在普通元素上时,只能监听原生 DOM 事件。用在自定义元素组件上时,也可以监听子组件触发的自定义事件

2.2.9 v-bind

v-bind用于绑定数据和元素属性,可以缩写为: 或.(当使用 .prop 修饰符时),比如

<div :someProperty.prop="someObject"></div>
<!-- 相当于 -->
<div .someProperty="someObject"></div>

v-bind的3个修饰符

  • .camel - 将 kebab-case attribute 名转换为 camelCase

  • .prop - 将一个绑定强制设置为一个 DOM property。3.2+

  • .attr - 将一个绑定强制设置为一个 DOM attribute。3.2+

2.2.10 v-model

v-model限制于:

components

v-model的3个修饰符:

  • .lazy - 惰性更新,监听 change 而不是 input 事件

  • .number - 输入字符串转为有效的数字

  • .trim - 输入首尾空格过滤

在表单控件或者组件上可以创建双向绑定,例如:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

2.2.11 v-slot

v-slot用于提供具名插槽或需要接收 prop 的插槽

可选择性传递参数,表示插槽名,默认值default

2.2.12 v-pre

v-pre指令用于跳过这个元素及其子元素的编译过程,例如:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

可以看到里头的东西没有被编译

2.2.13 v-cloak

v-cloak指令主要用于解决插值表达式在页面闪烁问题

<div v-cloak>
  {{ message }}
</div>
[v-cloak] {
  display: none;
}

这样div只会在编译结束后显示

2.2.14 v-once

v-once指令用于表示只渲染一次,当要重新渲染,元素/组件及其所有的子节点将被视为静态内容并跳过

2.2.15 v-memo 3.2+

用于缓存一个模板的子树

该指令接收一个固定长度的数组作为依赖值进行记忆比对。如果数组中的每个值都和上次渲染的时候相同,则整个该子树的更新会被跳过

<div v-memo="[valueA, valueB]"></div>

在重新渲染时,如果 valueA 与 valueB 都维持不变,那么对这个

以及它的所有子节点的更新都将被跳过

2.2.16 v-is

已在 3.1.0 中废弃,改用:is

<component :is="currentView"></component>

3. 自定义指令

3.1 如何自定一个指令

3.1.1 全局自定义指令

前言部分我们也说了,在Vue3中可以通过应用实例身上的directive()注册一个全局自定义指令。例如官方给的一个例子

const app = Vue.createApp({})
// 注册一个全局自定义指令 `v-focus`
app.directive(&#39;focus&#39;, {
  // 当被绑定的元素挂载到 DOM 中时……
  mounted(el) {
    // 聚焦元素
    el.focus()
  }
})

上述代码中,通过Vue.createApp({})得到应用实例app,应用实例app身上有个directive(),用于创建一个全局的自定义指令

用的时候也非常简单,例如

<input v-focus />

3.1.2 注册局部指令

如果想注册局部指令,可在组件中配置directives选项来注册局部指令;还是以v-focus为例:

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

3.1.3 疑问

通过上述例子,我们可以看到不管是使用directive自定义全局指令,还是使用directives配置局部指令,里头都需要一个指令名,如focus

而具体的配置对象中的mounted是啥?mounted中的el又是啥?除了mounted还有啥,除了el还有哪些参数?

3.1.4 钩子函数(7个)

开门见山,mounted其实就是指令的钩子函数,表示组件被挂载后调用;el则是指令绑定到的元素

这里主要讲讲钩子函数,除了mounted以外,还有其他指令钩子,均为可选

  • created:在绑定元素的 attribute 或事件监听器被应用之前调用

  • beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用

  • mounted:在绑定元素的父组件被挂载后调用

  • beforeUpdate:在更新包含组件的 VNode 之前调用

  • updated:在包含组件的 VNode及其子组件的 VNode更新后调用

  • beforeUnmount:在卸载绑定元素的父组件之前调用

  • unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次

3.1.5 钩子函数的4个参数

钩子函数的4个参数都是可选,分别是

el:用于直接操作 DOM,表示指令绑定到的元素

binding对象:包含以下6个属性

  • instance:使用指令的组件实例

  • value:传递给指令的值

  • oldValue:先前的值

  • arg:传递给指令的参数

  • modifiers:传递给指令的修饰符

  • dir:一个对象,其实就是注册指令时传递的配置对象

vnode:虚拟DOM,一个真实 DOM 元素的蓝图,对应el

prevNode:上一个虚拟节点

3.2 手动封装自定义指令

了解了基本知识,我们可以手动封装一个自定义指令v-pin,表示将一个东西定在页面上

3.2.1 创建Vue项目

首先,使用vite搭建Vue3项目

npm init vite@latest

最后根据提示,使用npm run dev启动项目

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

当然你也可以用其他方

我们知道Vue 自定义指令有全局注册和局部注册两种方式,为了方便,我就将v-pin注册在全局

3.2.2 实现效果

我要讲任意的定在指定的位置,比如将上图中的logo定位在右上角,代码如下:

//main.js
import { createApp } from &#39;vue&#39;
import App from &#39;./App.vue&#39;
const app = createApp(App)
app.directive(&#39;pin&#39;, {
    mounted(el, binding) {
        //是否要定住
        var pinned = binding.value;
        //传入的修饰符,表示定在哪里
        var position = binding.modifiers;
        // 传递给指令的参数,可以表示定在的重要度
        var args = binding.arg;
        if (pinned) {
            el.style.position = &#39;fixed&#39;;
            if (args == "warning") {
                //简单设置样式,以示区分
                el.style.backgroundColor = "pink";
            }
            for (var val in position) {
                if (position[val]) {
                    el.style[val] = &#39;10px&#39;;
                }
            }
        } else {
            el.style.position = &#39;static&#39;;
            el.style.backgroundColor = "";
        }
    }
})
app.mount(&#39;#app&#39;)

使用也很简单,如下

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

结果如图:

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

3.2.3 完善结构

为了方便以后注册更多的自定义指令,我们修改代码结构

首先,新创建一个专门用于放指令的文件夹directives

然后将每个自定义指令写成一个对象并导出,如下directives\pin.js

const pin = {
  mounted(el, binding) {
    //是否要定住
    var pinned = binding.value;
    //传入的修饰符,表示定在哪里
    var position = binding.modifiers;
    // 传递给指令的参数,可以表示定在的重要度
    var args = binding.arg;
    if (pinned) {
      el.style.position = &#39;fixed&#39;;
      if (args == "warning") {
        el.style.backgroundColor = "pink";
      }
      for (var val in position) {
        if (position[val]) {
          el.style[val] = &#39;10px&#39;;
        }
      }
    } else {
      el.style.position = &#39;static&#39;;
      el.style.backgroundColor = "";
    }
  }
}
export default pin

接着,在directives文件夹下创建index.js,将所有的指令都导入到这,放在directives中,然后导出一个install方法

import pin from &#39;./pin&#39;
const directives = {
    pin
}
export default {
    install(app) {
        Object.keys(directives).forEach((key) => {
            app.directive(key, directives[key])
        })
    },
}

最后就是在main.js中,通过use()来调用install方法,于是将所有的指令批量注册了

import { createApp } from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import Directives from &#39;./directives&#39;
const app = createApp(App)
app.use(Directives)
app.mount(&#39;#app&#39;)

刷新之后,结果还是一样

Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions

好处是,以后再写自定义指令就方便太多了

相关推荐:vue.js视频教程

The above is the detailed content of Learn about 16 Vue instructions from scratch to manually encapsulating custom instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete