<script>
let id = 0
export default {
data() {
return {
newTodo: '',
hideCompleted: false,
todos: [
{ id: id++, text: 'aaa', done: true },
{ id: id++, text: 'bb', done: true },
{ id: id++, text: 'cc', done: false }
]
}
},
computed: {
filteredTodos() {
return this.hideCompleted
? this.todos.filter(d => !d.done)
: this.todos
}
},
methods: {
addTodo() {
this.todos.push({ id: id++, text: this.newTodo, done: false})
this.newTodo = ''
},
removeTodo(todo) {
this.todos = this.todos.filter(d => d !== todo)
}
}
}
</script>
<template>
<div>
<form @submit.prevent="addTodo">
<input v-model="newTodo">
<button>Add todo</button>
</form>
<ul>
<li v-for="todo in filteredTodos" :key="todo.id">
<input type="checkbox" v-model="todo.done"/>
<span :class="{ done: todo.done }"></span>
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted"></button>
</div>
</template>
<style>
.done {
text-decoration: line-through;
}
</style>
组件挂载之后可以访问dom引用
<script>
export default {
mounted() {
this.$refs.p.textContent = 'mounted'
}
}
</script>
<template>
<p ref="p">Hello</p>
</template>
参考vue生命周期
export default {
watch: {
count(newCount) {
console.log(`new count is: ${newCount}`);
}
}
}
<script>
import ChildComp from './ChildComp.vue'
export default {
compunents: {
ChildComp,
},
data() {
return {
childMsg: 'msg',
}
}
}
</script>
<template>
<ChildComp :msg="greeting" @response="msg => childMsg = msg"/>
</template>
<script>
export default {
emits: ['response'],
created() {
this.$emit('response', 'hello from child')
},
props: {
msg: String,
}
}
</script>
子组件中使用<slot>fallback content</slot>
允许父组件在子元素中显示内容。类似react的{children}