指令 (Directives) 是带有 v- 前缀的特殊 attribute。指令 attribute 的值预期是单个 JavaScript 表达式 (v-for 是例外情况,稍后我们再讨论)。指令的职责是,当表达式的值改变时,将其产生的连带影响,响应式地作用于 DOM。
| 常用指令 | 参数类型 | 用法 |
|---|---|---|
| v-show | boolean | |
| v-if | boolean | |
| v-for | Iterable | |
| v-on | event | |
| v-bind | ||
| v-model |
v-on
绑定事件监听器。事件类型由参数指定。表达式可以是一个方法的名字或一个内联语句。用在普通元素上时,只能监听原生 DOM 事件。用在自定义元素组件上时,也可以监听子组件触发的自定义事件。
<!-- 方法处理器 --><button v-on:click="doThis"></button><!-- 动态事件 (2.6.0+) --><button v-on:[event]="doThis"></button><!-- 内联语句 --><button v-on:click="doThat('hello', $event)"></button><!-- 缩写 --><button @click="doThis"></button><!-- 动态事件缩写 (2.6.0+) --><button @[event]="doThis"></button><!-- 停止冒泡 --><button @click.stop="doThis"></button><!-- 阻止默认行为 --><button @click.prevent="doThis"></button><!-- 阻止默认行为,没有表达式 --><form @submit.prevent></form><!-- 串联修饰符 --><button @click.stop.prevent="doThis"></button><!-- 键修饰符,键别名 --><input @keyup.enter="onEnter" /><!-- 键修饰符,键代码 --><input @keyup.13="onEnter" /><!-- 点击回调只会触发一次 --><button v-on:click.once="doThis"></button><!-- 对象语法 (2.4.0+) --><button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
v-bind
动态地绑定一个或多个 attribute,或一个组件 prop 的表达式。在绑定 class 或 style attribute 时,支持其它类型的值,如数组或对象。
<!-- 绑定一个 attribute --><img v-bind:src="imageSrc" /><!-- 动态 attribute 名 (2.6.0+) --><button v-bind:[key]="value"></button><!-- 缩写 --><img :src="imageSrc" /><!-- 动态 attribute 名缩写 (2.6.0+) --><button :[key]="value"></button><!-- 内联字符串拼接 --><img :src="'/path/to/images/' + fileName" /><!-- class 绑定 --><div :class="{ red: isRed }"></div><div :class="[classA, classB]"></div><div :class="[classA, { classB: isB, classC: isC }]"></div><!-- style 绑定 --><div :style="{ fontSize: size + 'px' }"></div><div :style="[styleObjectA, styleObjectB]"></div><!-- 绑定一个全是 attribute 的对象 --><div v-bind="{ id: someProp, 'other-attr': otherProp }"></div><!-- 通过 prop 修饰符绑定 DOM attribute --><div v-bind:text-content.prop="text"></div><!-- prop 绑定。“prop”必须在 my-component 中声明。--><my-component :prop="someThing"></my-component><!-- 通过 $props 将父组件的 props 一起传给子组件 --><child-component v-bind="$props"></child-component><!-- XLink --><svg><a :xlink:special="foo" /></svg>
