Vue必备小知识-Vue 组件 component 实践小栗子
2023-12-24 22:40:15
Vue 组件 component 实践小栗子
在上一篇文章中,我们学习了 Vue 组件的概念和组件传值,并做了一些简单的练习。在这篇文章中,我们将进一步学习如何使用 Vue 组件来实现一个简单的待办事项列表,以及如何优化组件代码,以提高性能。
1. 创建 Vue 组件
首先,我们需要创建一个 Vue 组件。在组件中,我们将定义组件的模板和逻辑。
// TodoListItem.vue
<template>
<li>
<input type="checkbox" v-model="checked">
<span>{{ text }}</span>
<button @click="remove">X</button>
</li>
</template>
<script>
export default {
props: ['text'],
data() {
return {
checked: false
}
},
methods: {
remove() {
this.$emit('remove', this.text)
}
}
}
</script>
在这个组件中,我们定义了一个带有复选框、文本和删除按钮的待办事项项模板。在组件的逻辑中,我们定义了一个 checked
数据属性,用于跟踪待办事项是否已完成。我们还定义了一个 remove
方法,用于从列表中删除待办事项。
2. 使用 Vue 组件
现在我们已经创建了 Vue 组件,我们可以开始在我们的应用程序中使用它了。
// App.vue
<template>
<div>
<input type="text" v-model="newTodo">
<button @click="addTodo">添加</button>
<ul>
<todo-list-item v-for="todo in todos" :text="todo" @remove="removeTodo"></todo-list-item>
</ul>
</div>
</template>
<script>
import TodoListItem from './TodoListItem.vue'
export default {
components: {
TodoListItem
},
data() {
return {
todos: [],
newTodo: ''
}
},
methods: {
addTodo() {
this.todos.push(this.newTodo)
this.newTodo = ''
},
removeTodo(text) {
this.todos = this.todos.filter(todo => todo !== text)
}
}
}
</script>
在这个组件中,我们定义了一个带有输入框、添加按钮和待办事项列表的模板。在组件的逻辑中,我们定义了 todos
和 newTodo
数据属性,用于跟踪待办事项列表和新的待办事项。我们还定义了 addTodo
和 removeTodo
方法,用于向列表中添加和删除待办事项。
3. 优化组件代码
现在我们已经实现了一个简单的待办事项列表,我们可以对组件代码进行优化,以提高性能。
一种优化方法是使用缓存。我们可以使用 Vue 的 computed
属性来缓存计算结果。例如,我们可以使用 computed
属性来缓存待办事项列表的长度:
// App.vue
<script>
import TodoListItem from './TodoListItem.vue'
export default {
components: {
TodoListItem
},
data() {
return {
todos: [],
newTodo: ''
}
},
computed: {
todoCount() {
return this.todos.length
}
},
methods: {
addTodo() {
this.todos.push(this.newTodo)
this.newTodo = ''
},
removeTodo(text) {
this.todos = this.todos.filter(todo => todo !== text)
}
}
}
</script>
这样,我们就不需要在每次渲染组件时都重新计算待办事项列表的长度。
另一种优化方法是使用批处理更新。我们可以使用 Vue 的 nextTick
方法来批处理更新组件。例如,我们可以使用 nextTick
方法来批处理更新待办事项列表:
// App.vue
<script>
import TodoListItem from './TodoListItem.vue'
export default {
components: {
TodoListItem
},
data() {
return {
todos: [],
newTodo: ''
}
},
methods: {
addTodo() {
this.todos.push(this.newTodo)
this.newTodo = ''
this.$nextTick(() => {
this.todos = this.todos.sort()
})
},
removeTodo(text) {
this.todos = this.todos.filter(todo => todo !== text)
}
}
}
</script>
这样,我们就不会在每次向列表中添加或删除待办事项时都重新渲染组件。
通过使用缓存和批处理更新,我们可以优化组件代码,以提高性能。