Vue.js开发实践(3)-指令的使用

版权声明:需要引用、发表的朋友请与本人联系 https://blog.csdn.net/pbrlovejava/article/details/84870251


更多关于Vue.js的系列文章请点击Vue.js开发实践(0)-目录页


一、Vue指令

指令 (Directives) 是带有v-前缀的特殊特性。在Vue.js中,指令的作用是代替一段JS表达式,帮助开发者快速地完成简单的Dom操作。

1.1、v-if\else\else if

v-if是一个根据条件进行渲染的组件,使用方法如下:

 <div id="vue3" >
    	<div v-if='look == 1' v-html="message"></div>
 </div>
new Vue({
	el: '#vue3',
	data: {
		message: '<h1>Hello World!</h1>',
		look: 1
	}
})

还可以用 v-else 添加一个“else 块”:

<h1 v-if="ok">Yes</h1>
<h1 v-else>No</h1>

v-else-if,顾名思义,充当 v-if 的“else-if 块”,可以连续使用:

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

1.2、v-for

基于源数据多次渲染元素或模板块。此指令之值,必须使用特定语法 alias in expression ,为当前遍历的元素提供别名:

<div v-for="item in items">
  {{ item.text }}
</div>

另外也可以为数组索引指定别名 (或者用于对象的键):

<div v-for="(item, index) in items"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, key, index) in object"></div>
<div id="vue9">
		<ol v-for='(person,index) in personList'>
			<li>{{index}}:{{person.name}}:{{person.age}}</li> 
		</ol>
    </div>
new Vue({
	el: '#vue9',
	data: {
		personList: [
			{name: 'arong',age: 12},
			{name: 'lisa',age: 12},
			{name: 'lucy',age: 12}
		]
	}
})

在这里插入图片描述

1.3、v-on

绑定事件监听器,事件类型由参数指定。表达式可以是一个方法的名字或一个内联语句,如果没有修饰符也可以省略。

<div id="vue10">
		<button v-on:click='func(123)'>提交</button>
</div>

new Vue({
	el: '#vue10',
	methods: {
		func: function(text){
			alert(text);
		}
	}
})

详细的使用:

<!-- 方法处理器 -->
<button v-on:click="doThis"></button>

<!-- 内联语句 -->
<button v-on:click="doThat('hello', $event)"></button>

<!-- 缩写 -->
<button @click="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>

1.4、v-model

你可以用 v-model 指令在表单 、 及 元素上创建双向数据绑定。

<div id="vue11">
		<input type="text" name="t1" v-model='message1'>
		<h1>输入的字符串为:{{message1}}</h1>
	</div>

new Vue({
	el: '#vue11',
	data: {
		message1: ''
	}
})

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/pbrlovejava/article/details/84870251
今日推荐