文章目录
- vue的内置指令
- 说明:
- 自定义指令
vue的内置指令
Vue 指令的本质是:
- 声明式的 DOM 操作接口(隐藏底层 JavaScript 代码)。
- 响应式数据的绑定媒介(连接数据和视图)。
- 模板编译的标记(最终转换为渲染函数逻辑)。
- 可扩展的语法糖(简化复杂操作,如 v-model)。
通过指令,Vue 实现了 数据驱动视图 的核心思想,让开发者更专注于业务逻辑而非手动操作 DOM。
指令名称 | 简写形式 | 描述 | 示例 |
---|---|---|---|
v-bind | : | 动态绑定属性或组件 prop | :src="url" 或 v-bind:class="cls" |
v-on | @ | 绑定事件监听器 | @click="handleClick" 或 v-on:input |
v-model | 无 | 双向数据绑定(表单输入和组件) | v-model="message" |
v-for | 无 | 列表渲染(循环生成元素) | v-for="item in items" |
v-if | 无 | 条件渲染(根据条件销毁/创建元素) | v-if="isVisible" |
v-show | 无 | 显示/隐藏元素(通过 CSS 的 display 控制) | v-show="hasError" |
v-html | 无 | 输出原始 HTML(注意 XSS 风险) | v-html="rawHtml" |
v-text | 无 | 更新元素的 textContent (覆盖内容) | v-text="message" |
v-pre | 无 | 跳过该元素及其子元素的编译(显示原始 Mustache 标签) | <div v-pre>{{ 不会被编译 }}</div> |
v-cloak | 无 | 隐藏未编译的 Mustache 标签(需配合 CSS 使用) | [v-cloak] { display: none } |
v-once | 无 | 一次性渲染(元素/组件只渲染一次,后续数据变化不更新) | <span v-once>{{ staticText }}</span> |
v-slot | # | 定义插槽模板(用于具名插槽或作用域插槽) | <template #header>...</template> |
说明:
v-bind
和v-on
:最常用的简写指令,:
用于动态绑定,@
用于事件监听。v-model
:语法糖,等价于v-bind:value
+v-on:input
的组合。v-slot
:在 Vue 3 中简写为#
,常用于具名插槽或作用域插槽。- 特殊指令:如
v-pre
、v-cloak
、v-once
用于优化或控制编译过程。
示例
<template><div><h2>v-text</h2><div v-text="'hello vue'">hello world</div><h2>v-html</h2><div v-html="'<span style="color: red">hello vue</span>'">hello world</div><h2>v-show</h2><div v-show="show">hello vue</div><button @click="show = !show">change show</button><h2>v-if v-esle-if v-else</h2><div v-if="number === 1">hello vue {{ number }}</div><div v-else-if="number === 2">hello world {{ number }}</div><div v-else>hello geektime {{ number }}</div><h2>v-for v-bind</h2><div v-for="num in [1, 2, 3]" v-bind:key="num">hello vue {{ num }}</div><h2>v-on</h2><button v-on:click="number = number + 1">number++</button><h2>v-model</h2><input v-model="message"/><h2>v-pre</h2><div v-pre>{{ this will not be compiled }}</div><h2>v-once</h2><div v-once>{{ number }}</div></div>
</template>
<script>
export default {data: function () {this.log = window.console.log;return {show: true,number: 1,message: "hello"};}
};
</script>
自定义指令
<template><div><button @click="show = !show">销毁</button><!--自定义指令 v-append-text --><button v-if="show" v-append-text="`hello ${number}`" @click="number++">按钮</button></div>
</template>
<script>
export default {directives: {appendText: {bind() {console.log("bind");},inserted(el, binding) {el.appendChild(document.createTextNode(binding.value));console.log("inserted", el, binding);},update() {console.log("update");},componentUpdated(el, binding) {el.removeChild(el.childNodes[el.childNodes.length - 1]);el.appendChild(document.createTextNode(binding.value));console.log("componentUpdated");},unbind() {console.log("unbind");}}},data() {return {number: 1,show: true};}
};
</script>