vuejs指令详解(3)

<div> <div v-bind="{id:someProp,'OTHERATTR':otherProp}"></div> </div> <script type="text/javascript"> new Vue({ el: '#example', data: { someProp:'idName', otherProp:'prop' } }) </script>

结果如图:

在绑定prop时,prop必须在子组件中声明。可以用修饰符指定不同的绑定类型。修饰符为:

.sync——双向绑定,只能用于prop绑定。

.once——单次绑定,只能用于prop绑定。

.camel——将绑定的特性名字转换回驼峰命名。只能用于普通HTML特性的绑定,通常用于绑定用驼峰命名的SVG特性,比如viewBox。

v-on

v-on指令用于绑定事件监听器。事件类型由参数指定。

如果访问原始DOM事件,可以使用$event传入方法。

<button v-on:click="doThis('hello',$event)"></button> <!--缩写--> <button @click="doThis('hello',$event)"></button>

完整例子:

<div> <button v-on:click="greet">Greet</button> </div> var vm = new Vue({ el: '#example', data: { name: 'Vue.js' }, // 在 methods 对象中定义方法 methods: { greet: function (event) { // 方法内 this 指向 vm alert('Hello ' + this.name + '!') // event 是原生 DOM 事件 alert(event.target.tagName) } } }) // 也可以在 JavaScript 代码中调用方法 vm.greet(); // -> 'Hello Vue.js!'

###事件修饰符

<!-- 阻止单击事件冒泡 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 --> <form v-on:submit.prevent="onSubmit"></form> <!-- 修饰符可以串联 --> <a v-on:click.stop.prevent="doThat"> <!-- 只有修饰符 --> <form v-on:submit.prevent></form>

### 按键修饰符

<!-- 只有在 keyCode 是 13 时调用 vm.submit() --> <input v-on:keyup.13="submit"> <!-- 同上 --> <input v-on:keyup.enter="submit"> <!-- 缩写语法 --> <input @keyup.enter="submit">

全部的按键别名:enter,tab,delete,esc,space,up,down,left,right

v-ref

在父组件上注册一个子组件的索引,便于直接访问。不需要表达式,必须提供参数id。可以通过父组件的$refs对象访问子组件。

v-el

为DOM元素注册一个索引,方便通过所属实例的$els访问这个元素。可以用v-el:some-el设置this.$els.someEl。

<span v-el:msg>hello</span> <span v-el:other-msg>world</span>

通过this.$els获取相应的DOM元素:

this.$els.msg.textContent //'hello' this.$els.otherMsg.textContent //'world'

在新的vuejs中,简单起见, v-el 和 v-ref 合并为一个 ref 属性了,可以在组件实例中通过 $refs 来调用。

v-pre

跳过这个元素和它的子元素的编译过程。可以用来显示原始 Mustache 标签。跳过大量没有指令的节点会加快编译。

<span v-pre>{{ this will not be compiled }}</span>

v-cloak

这个指令保持在元素上直到关联实例结束编译。和 CSS 规则如 [v-cloak] { display: none } 一起用时,这个指令可以隐藏未编译的 Mustache 标签直到实例准备完毕。

css代码:

[v-cloak] { display: none; }

html:

<div v-cloak> {{ message }} </div>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgfzs.html