1.响应式
<script>
export default {
data(){
return{
message:'hello',
counter:{
count:1
}
}
}
}
</script>
<template>
<h1>{{message}}</h1>
<h1>{{counter.count}}</h1>
</template>
2.v-bind:缩写成:
<script>
export default {
data() {
return {
titleClass: 'title'
}
}
}
</script>
<template>
<h1 :class='titleClass'>Make me red</h1>
</template>
<style>
.title {
color: red;
}
</style>
3.v-on:缩写成@
<script>
export default {
data() {
return {
count: 0
}
},
methods:{
plus(){
this.count=this.count+1
}
}
}
</script>
<template>
<!-- 使此按钮生效 -->
<button @click='plus'>count is: {{ count }}</button>
</template>
4.v-model绑定
<script>
export default {
data() {
return {
text: ''
}
},
}
</script>
<template>
<input v-model='text'>
<p>{{ text }}</p>
</template>
5.条件渲染
<script>
export default {
data() {
return {
awesome: true
}
},
methods: {
toggle() {
this.awesome=!this.awesome
}
}
}
</script>
<template>
<button @click="toggle">toggle</button>
<h1 v-if='awesome'>Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
</template>
点击按钮来回切换
6.v-for
<script>
let id = 0
export default {
data() {
return {
newTodo: '',
todos: [
{ id: id++, text: 'Learn HTML' },
{ id: id++, text: 'Learn JavaScript' },
{ id: id++, text: 'Learn Vue' }
]
}
},
methods: {
addTodo() {
this.todos.push({id:id++,text:this.newTodo})
this.newTodo = ''
},
removeTodo(todo) {
this.todos=this.todos.filter(t=>t!=todo)
}
}
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
</template>
7.computed计算
<script>
let id = 0
export default {
data() {
return {
newTodo: '',
hideCompleted: false,
todos: [
{ id: id++, text: 'Learn HTML', done: true },
{ id: id++, text: 'Learn JavaScript', done: true },
{ id: id++, text: 'Learn Vue', done: false }
]
}
},
computed: {
filt(){
return this.hideCompleted ?
this.todos.filter(x=>!x.done) :
this.todos
}
},
methods: {
addTodo() {
this.todos.push({ id: id++, text: this.newTodo, done: false })
this.newTodo = ''
},
removeTodo(todo) {
this.todos = this.todos.filter((t) => t !== todo)
}
}
}
</script>
<template>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add Todo</button>
</form>
<ul>
<li v-for="todo in filt" :key="todo.id">
<input type="checkbox" v-model="todo.done">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted">
{{ hideCompleted ? 'Show all' : 'Hide completed' }}
</button>
</template>
<style>
.done {
text-decoration: line-through;
}
</style>
点击下面按钮,切换:隐藏完成/显示完成
8.组件
App.vue
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
}
}
</script>
<template>
<ChildComp />
</template>
ChildComp.vue
<template>
<h2>A Child Component!</h2>
</template>