When using Vue 3 to develop components, you can use the Composition API to define component logic and implement component value passing. The following is a detailed Vue 3
component example and explanation:
Suppose we want to develop a simple to-do list component, including the functions of adding to-do items, displaying to-do item list and deleting to-do items.
In the TodoList.vue file:
<template>
<div>
<input type="text" v-model="newTodo" placeholder="输入待办事项">
<button @click="addTodo">添加</button>
<ul>
<li v-for="(todo, index) in todos" :key="index">
{
{ todo }}
<button @click="deleteTodo(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
import {
ref } from 'vue';
export default {
name: 'TodoList',
setup() {
// 使用 ref 创建响应式数据
const newTodo = ref('');
const todos = ref([]);
// 添加待办事项
const addTodo = () => {
if (newTodo.value) {
todos.value.push(newTodo.value);
newTodo.value = '';
}
};
// 删除待办事项
const deleteTodo = (index) => {
todos.value.splice(index, 1);
};
// 暴露数据和方法给模板使用
return {
newTodo,
todos,
addTodo,
deleteTodo,
};
},
};
</script>
In the above example, we used Vue 3's Composition API to write components. It mainly includes the following parts:
- Use
ref
the function to create responsive data: We use the ref function to createnewTodo
andtodos
two responsive data, which are used to store the to-do item and the to-do list entered by the user respectively. - Define the method for adding to-do items: We define
addTodo
the method, which will be triggered when the user clicks the "Add" button. It willnewTodo
add the value of totodos
the list and clear the value of the input box. - Define the method to delete the todo: We define the deleteTodo method, which will be triggered when the user clicks the "Delete" button. It will remove the corresponding todo item from the todos list according to the passed index.
- Use responsive data and methods in the template: In the template, we use v-model to realize the two-way binding between the input box and newTodo, so that the value entered by the user can be updated synchronously. Use v-for to loop through the todos list and display each todo with its corresponding delete button.
In this way, we have completed the development of a simple to-do list component. When using this component elsewhere, it only needs to be imported and placed in the corresponding position. The data and methods inside the component have been encapsulated and can be used and passed in different contexts.