4. Develop TodoList using Composition API
Implement a simple add list
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Understand the cycle</title>
<! Vue library -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script></script>
</html>
Copy the code
The results
Encapsulation optimization
All the code written in setup is bloated, unreadable, and difficult to maintain
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Understand the cycle</title>
<! Vue library -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// Encapsulate the methods that handle the list
const handleList = () = > {
const { reactive } = Vue;
const list = reactive([]);
const addItem = (item) = > {
list.push(item);
}
return{ list, addItem }
}
// encapsulate a method to handle inputValue
const handleInputValue = () = > {
const { ref } = Vue;
const inputValue = ref('Eldest Brother Liu Bei');
return{ inputValue }
}
const app = Vue.createApp({
setup(){
const { list, addItem} = handleList();
const { inputValue } = handleInputValue();
return {
list, addItem, inputValue
}
},
template:
< button@click ="() => addItem(inputValue)"> Add
- {{item}} -- {{index}}
`
});
const vm = app.mount('#root');
</script>
</html>
Copy the code