在 Vue 中,指令是一种特殊的特性,用于在模板中对元素的行为进行操作和修改。以下是对一些主要 Vue 指令的详细用法介绍:
一、 v-bind 指令
1. 基本用法
- 用于动态地绑定一个或多个特性(attribute),或者将一个元素的属性与 Vue 实例中的数据进行绑定。
- 示例:
<img v-bind:src="imageUrl" />
- 可以简写成 : 的形式,如 <img :src="imageUrl" /> 。
2. 绑定对象属性
- 可以绑定对象的属性到元素的属性上。
- 示例:
<div v-bind:style="styleObject"></div>
- 在 Vue 实例中:
data() {
return {
styleObject: {
color: 'red',
fontSize: '20px'
}
};
}
3. 绑定计算属性
- 可以绑定计算属性到元素的属性上。
- 示例:
<div v-bind:class="computedClass"></div>
- 在 Vue 实例中:
data() {
return {
isActive: false
};
},
computed: {
computedClass() {
return {
active: this.isActive
};
}
}
二、 v-on 指令
1. 基本用法
- 用于绑定事件监听器。
- 示例:
<button v-on:click="handleClick">点击我</button>
- 可以简写成 @ 的形式,如 <button @click="handleClick">点击我</button> 。
2. 传递参数
- 可以向事件处理函数传递参数。
- 示例:
<button @click="handleClick('参数值')">点击传递参数</button>
- 在 Vue 实例中:
methods: {
handleClick(param) {
console.log(param);
}
}
3. 事件修饰符
- .stop :阻止事件冒泡。
- .prevent :阻止默认行为。
- .capture :使用事件捕获模式而不是默认的冒泡模式。
- .self :只当事件在该元素本身(而不是子元素)触发时触发回调。
- .once :事件将只会触发一次。
- 示例:
<a @click.prevent.stop="handleLinkClick">禁止默认跳转并阻止冒泡</a>
三、 v-if 、 v-else-if 和 v-else 指令
1. 基本用法
- 根据条件来渲染元素。 v-if 单独使用,当条件为真时渲染元素; v-else-if 和 v-else 与 v-if 配合使用,实现多条件判断。
- 示例:
<div v-if="showMessage">消息内容</div>
<div v-else-if="showWarning">警告内容</div>
<div v-else>默认内容</div>
- 在 Vue 实例中:
data() {
return {
showMessage: false,
showWarning: false
}
2. 动态切换
- 可以通过改变数据中的条件值来动态地切换显示的内容。
- 示例:
methods: {
toggle() {
this.showMessage =!this.showMessage;
this.showWarning =!this.showWarning;
}
}
四、 v-for 指令
1. 基本用法
- 基于一个数组来循环渲染元素。
- 示例:
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
- 在 Vue 实例中:
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
2. 遍历对象
- 可以遍历对象的属性。
- 示例:
<ul>
<li v-for="(value, key) in object" :key="key">{{ key }}: {{ value }}</li>
</ul>
- 在 Vue 实例中:
data() {
return {
object: {
name: 'Object Name',
property: 'Object Property'
}
};
}
3. 遍历数字范围
- 可以遍历一个数字范围。
- 示例:
<ul>
<li v-for="n in 5" :key="n">{{ n }}</li>
</ul>
五、自定义指令
1. 全局自定义指令
- 使用 Vue.directive() 方法创建全局自定义指令。
- 示例:
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
- 在模板中使用:
<input v-focus />
2. 局部自定义指令
- 在组件选项中定义局部自定义指令。
- 示例:
export default {
directives: {
'highlight': {
bind(el, binding, vnode) {
el.style.backgroundColor = binding.value;
}
}
},
//...
};
- 在模板中使用:
<div v-highlight="'yellow'">Highlight this div</div>
六、 v-model 指令
1. 基本用法
- 用于在表单元素上创建双向数据绑定。
- 示例:
<input v-model="message" />
- 在 Vue 实例中:
data() {
return {
message: ''
};
}
2. 修饰符
- .lazy :将绑定从“input”事件转换为“change”事件,在失去焦点或按回车键时更新数据。
- .number :将输入的值转换为数值类型。
- .trim :自动过滤用户输入的首尾空白字符。
- 示例:
<input v-model.lazy="message" />