当你谈论 Vue.js 时,你通常会谈到组件. 组件,组件,组件. 组件不是你可以用 Vue 写的唯一东西,但它也是一个好事。 如果你想将修改器应用到你的组件中,你会怎么办?这就是指令的出现。 无论你是否知道它,你都已经使用了它们。 v-if, v-model 和 v-for 都是指令的例子。 今天,我们将向你展示如何添加一个重要的指令,该指令执行一个关键任务,我们不能没有它。
制定一项指令
然后,让我们直接进入它的厚度。创建一个名为AnnoyingBackgroundDirective.js的新文件。
现在,让我们写下指令,指令只是一个对象,上面有一些特殊的功能。
1[label AnnoyingBackgroundDirective.js]
2import Vue from 'vue';
3
4const defaultBackgroundColor = '#86bbff'
5
6// Initialize the annoying-background directive.
7export const AnnoyingBackground = {
8 bind(el, binding, vnode) {
9 // Allow users to customise the color by passing an expression.
10 const color = binding.expression || defaultBackgroundColor
11
12 // el might not be present for server-side rendering.
13 if (el) {
14 // Set the element's background color.
15 el.style.backgroundColor = color
16 }
17 }
18}
19
20// You can also make it available globally.
21Vue.directive('annoying-background', AnnoyingBackground)
现在要在组件中使用它,只需将其添加到您的组件模板中,前缀为v-.
1[label TotallyNormalComponent.vue]
2<template>
3 <div>
4 <p v-annoying-background>Baby blue looks good on me.</p>
5 <p v-annoying-background="#0f0">I prefer neon green.</p>
6 </div>
7</template>
8
9<script>
10import { AnnoyingBackground } from './AnnoyingBackgroundDirective.js';
11
12export default {
13 directives: {
14 AnnoyingBackground
15 }
16}
17</script>
更多细节
一个指令有五种可能的陷阱:
bind(element, binding, vnode)
- 被称为当指令首先绑定到组件或元素时inserted(element, binding, vnode)
- 被称为当组件或元素被插入其母节点时。 它可能尚未在DOM中update(element, binding, vnode, oldVnode)
- 被称为当包含的组件已更新但潜在地在其子女之前componentUpdated(element, binding, vnode, oldVnode)
- 被称为当包含的组件已更新但其子孙后 `unbind(element, binding, vnode
论点是这些:
- `要素 ' -- -- 指令必须遵守的要素。 可能未定义。
约束' - (这是有趣的。 ) 包含向指令传递的任何参数、值和修改符。 (_) ) -
绑定.名' - 指令名称.(_) ) -- --约束.价值 ' -- -- 联合来文表达的价值转至指令(如果有的话)。 (e.'v-diction='{蛋糕:'chocolate'}")". - >
绑定值. cake QQ ' chocolate''
绑定值.old
价值- 该指令的上个价值,仅在 " 更新 " 和 " 更新 " 中提供。 (_) ) -
绑定. 表达式- 作为字符串的值表达式 :
v- directive={ cake:
chocolate}
- > 绑定。 表达式 {{ 蛋糕: 'chocolate'}}(_) )-
bonding.arg'- 论点转至指令(如果有的话)。v-方向:myArg' ->
约束.arg ===''my Arg' -约束.修改者' - 含有任何修饰符的对象以布尔语传递给指令 。
v-diction.modifer.modifer2' - >JSON.stringify (bonding.modifers) {'modifer: true,"modifer2": true *
vnode'-这是Vue的渲染器使用的虚拟节点. 除非知道自己在做什么,否则别碰这个。 : P
OldVnode'――上述
vnode'的前一个版本。 仅在更新钩中可用. ( (英语)
所以,是的,指令创建真的很简单,但如果你愿意,你可以用它们做很多疯狂的事情。
奖金轮
- 尝试创建条件指令! ** 提示:** 您可能需要连接到 vNode API。
此分類上一篇: 左: 36px;邊緣頂部: 9px;位置:絕對;邊緣頂部: 6px 固體透明;邊緣底: 6px 固體透明;邊緣左: 4px 固體 #EFBB35;邊緣頂部: 4px 固體 #EFBB35;邊緣底: 4px 固體 #EFBB35;邊緣右: 4px 固體 #EFBB35; } [itemprop=articleSection] 邊緣左: 4px 固體 #EFBB35;邊緣頂部: 4px 固體 #EFBB35;邊緣底: 4px 固體 #EFBB35; 邊緣右: 4px 固體 #EFBB35;