1.vue声明式渲染{{ message }}
<template><div id="App">{{message}}-{{syk}}</div></template>
export default {
name: "App",
data: {
message: 'hello ' ,
syk:122
}
}
2.v-if
<template>
<div id="App">
<p v-if="seen">现在你看到我了</p>
</div></template>
export default {
name: "App",
data: {
seen: true
}
}
<template>
<div id="App">
<div v-if="seen">if</div> <div v-else>else</div>
</div>
</template>
export default {
name: "App",
data: {
seen: true
}
}
运行结果为if 当seen: false时运行结果为else
<template>
<div id="App">
<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>
</div>
</template>
export default {
name: "App",
data: { type: 'E' }
} 运行结果为Not A/B/C
v-show:
<div v-show="seen1">v-show</div>
data: {seen1: true} 运行结果为v-show
tips:v-if是动态的向DOM树内添加或者删除DOM元素;v-show是通过设置DOM元素的display样式属性控制显隐;
3.v-for
<template>
<div id="App">
<ol>
<li v-for="item in arr" :key="item.id">{{item.id}}--{{item.text}}</li>
</ol>
</div>
</template>
export default {
name: "App",
data: {
arr: [
{ text: '学习 JavaScript' },
{ text: '学习 Vue' },
{ text: '整个牛项目' }
]
}
}
tips:要写:key="" 否则会报错
v-for 还支持一个可选的第二个参数,即当前项的索引。
<template>
<div id="App">
<ul>
<!-- <li v-for="(item,index) of items" :key=item> -->
<li
v-for="(item,index) in items"
:key="item"
>{{ parentMessage }} - {{ index }} - {{ item.message }}</li>
</ul>
</div>
</template>
export default {
name: "App",
data:{
parentMessage: "Parent",
items: [{ message: "Foo" }, { message: "Bar" }],
}
}
用 v-for 来遍历一个对象
<template>
<div>
<ul id="v-for-object" class="demo">
<li v-for="(value,name, index) in object" :key="value">{{ index }}. {{ name }}: {{ value}}</li>
</ul>
</div>
</template>
export default {
name: "App",
data: {
object: {
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10' }
}
}
4.v-on:click
<template>
<div id="App">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">反转消息</button>
</div>
</template>
export default {
name: "App",
data: { message: 'hello' },
}
methods: {
reverseMessage: function(){
this.message = this.message.split('').reverse().join('')
}
}
tips:v-on:click="reverseMessage"可简写为@click="reverseMessage"
5.v-model双向绑定
<template>
<div id="App">
<p>{{ message }}</p>
<input v-model="message">
</div>
</template>
export default {
name: "App",
data: { message: 'Hello Vue!' }
}