What is the vue directive?

青灯夜游
Release: 2022-08-26 19:02:58
Original
5533 people have browsed it

In vue, a directive is a special feature (attribute) with the "v-" prefix. The value of the directive property is expected to be a single JavaScript expression, and the syntax is "v-directive: parameter="expression" ". Vue acts on HTML elements, and directives provide some special features. When binding directives to elements, directives will add some special behaviors to the bound target elements; therefore directives can be regarded as special HTML features.

What is the vue directive?

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

1. What is the vue.js command? What is the function?

Vue.js Directives are special features with v- prefix. The value of a directive attribute is expected to be a single JavaScript expression (v-for is the exception).

Vue.js acts on HTML elements. The directive provides some special features. When the directive is bound to an element, the directive will add some special behaviors to the bound target element. We can view the directive Make special HTML attributes. The function of the

directive is: when the value of the expression changes, its associated effects are applied to the DOM in a responsive manner.

Each instruction has its own purpose. When its bound expression changes, it will affect the DOM changes in a responsive manner. The specific changes depend on the purpose of each instruction. For example, the v-bind instruction binds attribute values. When the binding expression changes, the value of the attribute on the DOM will also change accordingly. The syntax of the

command is : v-command: parameter="expression" (the parameter is not absolutely required)

Parameters

: is followed by parameters, but not all instructions will have parameters. Only specific instructions will require parameters. This is Determined by the nature of the instruction. The parameters here are similar to the parameters of the function, just like my command requires corresponding parameters to make the function effective.

Take v-bind:type="type" as an example, the v-bind instruction is used to bind attribute values, so what attributes need to be bound? This command alone cannot determine, so parameters are needed to further determine. That is, v-bind:type, the type followed by the colon is the parameter passed in the instruction. Tell the directive that I want to bind the association between attribute type and expression.

As we said above, not all instructions require parameters. For example, the v-html instruction is the html inside the binding element. The function point is very clear. No additional parameters are needed to determine it. Only instructions and expressions are needed. Complete the function of the instruction.

Expression

""The value within the quotation marks is the expression. The expression can generally be an executable js expression. It is bound to the instruction itself, similar to the value passed into the instruction. And when the responsive data in the expression changes, it will also cause changes in the dom.

2. Built-in instructions

##2.1 What are the built-in instructions in Vue?

The built-in instructions refer to

Vue Comes with built-in commands, ready to use out of the box

VueThere are a total of 16 built-in commands, including:

v-text v-htmlv-showv-ifv-elsev-else -ifv-forv-onv-bindv-modelv -slotv-prev-cloakv-oncev-memov -is, where v-memo is newly added in 3.2, v-is was abandoned# in 3.1.0 ##Let’s learn about the basic use of these built-in instructions

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

2.2.1 v -text

v-text

is used to update the textContent of the element, for example: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;h1&gt;&lt;/h1&gt;</pre><div class="contentsignin">Copy after login</div></div>

h1 The content of the

element ultimately depends on the value of msg

What is the vue directive?##2.2.2 v-html

Much like v-text

, except

v-html is used to update the element's innerHTML, such as

<div>Hello LBJ'"></div>
Copy after login

It should be noted that the content must be inserted as normal What is the vue directive?HTML

2.2.3 v-show

v-show

can switch the

display value of the element according to the true or false value of the expression, which is used to control the display and hiding of the element, for example:

可以看到,当条件变化时该指令触发显示或隐藏的过渡效果

需要注意:v-show 不支持 <template></template> 元素,也不支持 v-else

2.2.4 v-if

v-if用于根据表达式的真假值来有条件地渲染元素

v-show相比,v-if在切换时是元素的销毁或重建,而不是简单的显示隐藏

What is the vue directive?

可以看到当表达式为假时,v-if是直接销毁元素,而v-show只是视觉上隐藏了而已

并且v-if可以是 <template></template>,如果元素是 <template></template>,将提取它的内容作为条件块

2.2.5 v-else

v-else无需表达式,表示添加一个“else 块”,相当于v-if满足条件时展示v-if的元素,否则展示v-else的元素,例如:

What is the vue directive?

需要注意:v-else前一个兄弟元素必须有 v-if v-else-if

2.2.6 v-else-if

同理,表示 v-if 的“else if 块”,和v-else一样,前一个兄弟元素必须有v-ifv-else-if,例如:

What is the vue directive?

2.2.7 v-for

v-for一个用于迭代的指令,可以根据源数据多次渲染元素或模板块,例如:

What is the vue directive?

也可以为数组索引指定别名或者用于对象的键

<div></div>
<div></div>
<div></div>
Copy after login

2.2.8 v-on

v-on用于给元素绑定事件,可以缩写为:@

修饰符

  • .stop - 调用 event.stopPropagation()
  • .prevent - 调用 event.preventDefault()
  • .capture - 添加事件侦听器时使用 capture 模式
  • .self - 只当事件是从侦听器绑定的元素本身触发时才触发回调
  • .{keyAlias} - 仅当事件是从特定键触发时才触发回调
  • .once - 只触发一次回调
  • .left - 只当点击鼠标左键时触发
  • .right - 只当点击鼠标右键时触发
  • .middle - 只当点击鼠标中键时触发
  • .passive - { passive: true } 模式添加侦听器

例如:

<!-- 停止冒泡 -->
<button></button>
Copy after login

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

2.2.9 v-bind

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

<div></div>
<!-- 相当于 -->
<div></div>
Copy after login

v-bind3个修饰符

  • .camel - 将 kebab-case attribute 名转换为 camelCase
  • .prop - 将一个绑定强制设置为一个 DOM property。3.2+
  • .attr - 将一个绑定强制设置为一个 DOM attribute。3.2+

2.2.10 v-model

v-model限制于:&lt;input&gt;<select></select><textarea></textarea>components

v-model3个修饰符:

  • .lazy - 惰性更新,监听 change 而不是 input 事件
  • .number - 输入字符串转为有效的数字
  • .trim - 输入首尾空格过滤

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

What is the vue directive?

2.2.11 v-slot

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

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

2.2.12 v-pre

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

What is the vue directive?

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

2.2.13 v-cloak

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

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

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

2.2.14 v-once

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

2.2.15 v-memo 3.2+

用于缓存一个模板的子树

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

<div></div>
Copy after login

在重新渲染时,如果 valueA 与 valueB 都维持不变,那么对这个 <div> 以及它的所有子节点的更新都将被跳过<h4 data-id="heading-23"><strong>2.2.16 v-is</strong></h4> <p>已在 3.1.0 中废弃,改用<code>:is

<component></component>
Copy after login

3、自定义指令

3.1 如何自定一个指令

3.1.1 全局自定义指令

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

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

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

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

&lt;input&gt;
Copy after login

3.1.2 注册局部指令

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

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

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:一个对象,其实就是注册指令时传递的配置对象
Copy after login
  • vnode:虚拟DOM,一个真实 DOM 元素的蓝图,对应el
  • prevNode:上一个虚拟节点

3.2 手动封装自定义指令

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

3.2.1 创建Vue项目

首先,使用vite搭建Vue3项目

npm init vite@latest
Copy after login

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

What is the vue directive?

当然你也可以用其他方

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

3.2.2 实现效果

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

//main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

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

app.mount('#app')
Copy after login

使用也很简单,如下

1What is the vue directive?

结果如图:

1What is the vue directive?

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 = 'fixed';
      if (args == "warning") {
        el.style.backgroundColor = "pink";
      }
      for (var val in position) {
        if (position[val]) {
          el.style[val] = '10px';
        }
      }
    } else {
      el.style.position = 'static';
      el.style.backgroundColor = "";
    }
  }
}
export default pin
Copy after login

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

import pin from './pin'
const directives = {
    pin
}
export default {
    install(app) {
        Object.keys(directives).forEach((key) => {
            app.directive(key, directives[key])
        })
    },
}
Copy after login

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

import { createApp } from 'vue'
import App from './App.vue'
import Directives from './directives'


const app = createApp(App)

app.use(Directives)

app.mount('#app')
Copy after login

刷新之后,结果还是一样

What is the vue directive?

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

(学习视频分享:web前端入门vue视频教程

The above is the detailed content of What is the vue directive?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template