File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 88 autofocus =" "
99 autocomplete =" off"
1010 placeholder =" What needs to be done?"
11+ v-model =" newTodoRef"
12+ @keyup.enter =" addTodo"
1113 />
14+ <!-- 通过 enter 修饰符,当回车时 -->
1215 </header >
1316 <section class =" main" >
1417 <input id =" toggle-all" class =" toggle-all" type =" checkbox" />
5962</template >
6063
6164<script >
62- import { ref , watchEffect } from " vue" ;
63- import * as todoStorage from " ./utils/todoStorage" ;
65+ import { useNewTodo , useTodoList } from " ./components" ;
6466
6567export default {
6668 setup () {
67- const todoRef = ref (todoStorage .fetchTodos ());
68- // 监控副作用
69- // 在 watch 中读取的会自动收集依赖
70- // 当依赖变化时会自动运行该副作用函数
71- watchEffect (() => {
72- todoStorage .saveTodos (todoRef .value );
73- });
69+ const { todoRef } = useTodoList ();
70+ return {
71+ // todoRef: todoList.todoRef,
72+ todoRef,
73+ ... useNewTodo (todoRef),
74+ };
7475 },
7576};
7677 </script >
Original file line number Diff line number Diff line change 1- export { default as useCount } from './useCount'
1+ export { default as useCount } from './useCount'
2+ export { default as useNewTodo } from './useNewTodo'
3+ export { default as useTodoList } from './useTodoList'
Original file line number Diff line number Diff line change 1+ import { ref } from "vue" ;
2+ import { generateID } from "../utils/todoStorage" ;
3+
4+ export default function useNewTodo ( todoRef ) {
5+ const newTodoRef = ref ( "" ) // 到时候 v-model 绑定到输入框上,获取新任务内容
6+
7+ const addTodo = ( ) => {
8+ const val = newTodoRef . value && newTodoRef . value . trim ( )
9+ if ( ! val ) return
10+ const newTodoObj = {
11+ title : val ,
12+ completed : false ,
13+ id : generateID ( )
14+ }
15+ todoRef . value . push ( newTodoObj ) // 注意 setup 中是对象得手动解一层
16+ newTodoRef . value = "" ; // 清空输入框
17+ }
18+
19+ return {
20+ newTodoRef,
21+ addTodo
22+ }
23+ }
Original file line number Diff line number Diff line change 1+ import { ref , watchEffect } from "vue" ;
2+ import * as todoStorage from "../utils/todoStorage" ;
13
24export default function useTodoList ( ) {
5+ const todoRef = ref ( todoStorage . fetchTodos ( ) ) ;
6+ // 监控副作用
7+ // 在 watch 中读取的会自动收集依赖
8+ // 当依赖变化时会自动运行该副作用函数
9+ watchEffect ( ( ) => {
10+ todoStorage . saveTodos ( todoRef . value ) ;
11+ } ) ;
312
13+ return {
14+ todoRef
15+ }
416}
Original file line number Diff line number Diff line change @@ -18,4 +18,12 @@ export function fetchTodos() {
1818 */
1919export function saveTodos ( newTodos ) {
2020 localStorage . setItem ( TODOS_KEY , JSON . stringify ( newTodos ) )
21+ }
22+
23+ /**
24+ * 生成任务的唯一ID = 时间戳 + 随机数
25+ */
26+ export function generateID ( ) {
27+ return Date . now ( ) + Math . random ( ) . toString ( 16 ) . substring ( 2 , 6 )
28+ // 已经不推荐 substr 第二个参数为长度,推荐 substring 第二个参数为结束位置更直观
2129}
You can’t perform that action at this time.
0 commit comments