147.md 2.9 KB
Newer Older
W
wizardforcel 已提交
1
# 3 Vue 指令简介
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javabeginnerstutorial.com/vue-js/3-vue-directives/](https://javabeginnerstutorial.com/vue-js/3-vue-directives/)

W
wizardforcel 已提交
5
今天,我们将探讨 Vue 指令的全部内容。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
首先是第一件事。 什么是指令? 这些是特殊的说明,它们会在附加到 HTML 元素时更改其行为。 换句话说,这些是附加到 HTML 元素的特殊属性,这些属性可以更改行为并基于 DOM 的表达式值提供对 DOM 的控制。
W
init  
wizardforcel 已提交
8

W
wizardforcel 已提交
9
所有 Vue 指令均以`v-`为前缀。 该前缀用于以下目的:
W
init  
wizardforcel 已提交
10

W
wizardforcel 已提交
11
*   表示它是属于 Vue 的特殊属性
W
init  
wizardforcel 已提交
12 13 14
*   帮助保持语法一致
*   为开发人员提供可读性

W
wizardforcel 已提交
15
Vue 带有一些内置指令。 请注意,我们可以编写自己的自定义指令,我们将在以后看到。 这些指令可以在许多情况下为我们提供帮助。
W
init  
wizardforcel 已提交
16

W
wizardforcel 已提交
17
一些示例是,
W
init  
wizardforcel 已提交
18 19

*   单向和双向**绑定**`v-bind``v-model`
W
wizardforcel 已提交
20
*   **监听 DOM 事件**`v-on`
W
init  
wizardforcel 已提交
21 22 23 24 25
*   **条件渲染**`v-if``v-else``v-for`
*   **插值**`v-once``v-html``v-text`

在我们的教程系列中,我们将详细处理所有这些指令。 现在,让我们看一下`v-once`的工作,并提供一个代码示例,以大致了解指令的工作方式。

W
wizardforcel 已提交
26
## 场景:
W
init  
wizardforcel 已提交
27 28 29 30

*   显示标题和
*   显示带有问候消息的段落,例如“嗨!”

W
wizardforcel 已提交
31
### `Index.html`
W
init  
wizardforcel 已提交
32

W
wizardforcel 已提交
33
```js
W
init  
wizardforcel 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
<html>
  <head>
    <title>Hello Vue!</title>
    <!-- including Vue with development version CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h1>{{ message }}</h1>
      <p>Calling the greet function - {{ greet() }}!</p>
    </div>
    <!-- including index.js file-->
    <script src="index.js"></script>
  </body>
</html>
```

W
wizardforcel 已提交
51
### `Index.js`
W
init  
wizardforcel 已提交
52

W
wizardforcel 已提交
53
```js
W
init  
wizardforcel 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
var app = new Vue({
  el: "#app",
  data: {
    message: "Hi everyone!"
  },
  methods: {
    greet() {
      this.message = "Hi!"
      return this.message;
    }
  }
});
```

你能猜出输出吗?

W
wizardforcel 已提交
70
`greet()`函数返回的标题和值都将为“`Hi!`”。 因为一旦`message`的值更改,所有出现的事件都会被重新渲染。 这是默认行为。
W
init  
wizardforcel 已提交
71

W
wizardforcel 已提交
72
![without Vue Directives](img/b61c39cadd45c6bced82a8933db8cda1.png)
W
init  
wizardforcel 已提交
73

W
wizardforcel 已提交
74 75 76 77 78
但是,在某些情况下,即使稍后更改属性,您可能仍要显示其初始值。 这是指令生效的地方。 在我们的场景中,我们希望显示`message`属性的初始值“`Hi everyone!`” 作为标题。 因此,通过将指令`v-once`添加到`<h1>`元素,该元素内部的所有内容将仅呈现一次。 稍后通过`<p>`元素中的`greet()`方法对其进行更改时,将不会对其进行更新。

![With Vue directives](img/86f997c82e065ce6c4461f4bd6bd5bfb.png)

与往常一样,所有代码文件都可以在 [GitHub 仓库](https://github.com/JBTAdmin/vuejs)中找到。 请随意创建您自己的副本,以尝试使用`v-once`指令。 不要忘记让您的想象力疯狂。 再见!