vue简单语法练习
上一篇我们创建了一个vue的helloworld,这篇继续在helloVue文件中练习语法
1. v-if
v-if 指令用于条件性地渲染一块内容。这块内容只会在指令的表达式返回 truthy 值的时候被渲染。
<template>
<div>
<h1>Hello Vue!</h1>
<div v-if="ok">
I'll show
</div>
</div>
</template>
<script>
export default {
name: "helloVue",
data:function() {
return {
ok: false
};
}
}
</script>
设置ok变量值为true的时候的时候,<div v-if="ok"> I'll show </div>
被渲染出来,ok值为false时不会被渲染
v-else如果ok值为true显示i'am true,
ok值为false显示则执行v-else-if="no"判断no的值,为true则显示 I'am else if,为false则显示v-else的内容
<template>
<div>
<h1>Hello Vue!</h1>
<div v-if="ok">
I'am true
</div>
<div v-else-if="no">
I'am else if
</div>
<div v-else>
I'am flase
</div>
</div>
</template>
2. v-for
我们可以用 v-for 指令基于一个数组来渲染一个列表。v-for 指令需要使用 item in items 形式的特殊语法,其中 items 是源数据数组,而 item 则是被迭代的数组元素的别名。
<template>
<div>
<h1>Hello Vue!</h1>
<ul>
<li v-for="item in items" v-bind:key="item.id">
{{item.text}}----{{item.author}}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "helloVue",
data:function() {
return {
items:[
{id:0, text:'第一序列', author:'肘子'},
{id:1, text:'汉乡', author:'孑与2'},
{id:2, text:'明天下', author:'孑与2'},
{id:3, text:'斗破苍穹', author:'土豆'},
]
};
}
}
</script>
<style scoped>
h1{
color:#2c3e50;
}
</style>
在
v-for
里使用对象你也可以用
v-for
来遍历一个对象的属性。
<template>
<div>
<ul >
<li v-for="(value, index) in object" v-bind:key="index">
{{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "helloVue",
data:function() {
return {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
}
};
}
}
</script>
3. v-on
可以用 v-on
指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码。
<div>
<h1>Hello Vue!</h1>
<button v-on:click="counter += 1">+ 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>
</template>
<script>
export default {
name: "helloVue",
data:function() {
return {
counter: 0,
};
}
}
</script>
![](https://img.haomeiwen.com/i2982994/536bc6629d31d89f.gif)
4. v-model
你可以用 v-model 指令在表单 <input>
、<textarea>
及 <select>
元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但 v-model
本质上不过是语法糖。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。
<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
loading......
网友评论