Skip to content

Commit 2c36fc2

Browse files
committed
feat[ptr]: Vue3 将 LifeCycle Function 都抽离成普通函数了,不需要再限定在配置中
1 parent 0741168 commit 2c36fc2

3 files changed

Lines changed: 51 additions & 5 deletions

File tree

Vue3/sandboxs-vite/src/components/Todos.vue

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,22 @@
4949
<span>items left</span>
5050
</span>
5151
<ul class="filters">
52-
<li><a href="#/all" class="selected">All</a></li>
53-
<li><a href="#/active" class="">Active</a></li>
54-
<li><a href="#/completed" class="">Completed</a></li>
52+
<li>
53+
<!-- 注意动态 class 要用对象,同时别忘记 v-bind 的 : -->
54+
<a href="#/all" :class="{ selected: filterRef === 'all' }">All</a>
55+
</li>
56+
<li>
57+
<a href="#/active" :class="{ selected: filterRef === 'active' }"
58+
>Active</a
59+
>
60+
</li>
61+
<li>
62+
<a
63+
href="#/completed"
64+
:class="{ selected: filterRef === 'completed' }"
65+
>Completed</a
66+
>
67+
</li>
5568
</ul>
5669
<button class="clear-completed" style="display: none">
5770
Clear completed
@@ -62,7 +75,7 @@
6275
</template>
6376

6477
<script>
65-
import { useNewTodo, useTodoList } from "../compositions";
78+
import { useNewTodo, useTodoList, useFilter } from "../compositions";
6679
6780
export default {
6881
setup() {
@@ -71,6 +84,7 @@ export default {
7184
// todoRef: todoList.todoRef,
7285
todoRef,
7386
...useNewTodo(todoRef),
87+
...useFilter(todoRef),
7488
};
7589
},
7690
};
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export { default as useCount } from './useCount'
22
export { default as useNewTodo } from './useNewTodo'
3-
export { default as useTodoList } from './useTodoList'
3+
export { default as useTodoList } from './useTodoList'
4+
export { default as useFilter } from './useFilter'
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { ref, onMounted, onUnmounted } from "vue";
2+
3+
const filterEnum = ["all", "active", "completed"]
4+
5+
export default function useFilter(todoRef) {
6+
const filterRef = ref("all")
7+
8+
// 筛选方式响应 与 hash 连接
9+
const onHashChange = () => {
10+
// trim 左边不需要的 #/
11+
const hash = location.hash.replace(/#\/?/, "");
12+
if (filterEnum.includes(hash)) {
13+
filterRef.value = hash
14+
} else {
15+
filterRef.value = "all"
16+
location.hash = "" // "" 虽然是无效会第二次走到这分支,但是 "" => "" 不会触发 hashchange
17+
}
18+
}
19+
20+
onMounted(() => {
21+
window.addEventListener("hashchange", onHashChange)
22+
})
23+
24+
onUnmounted(() => {
25+
window.removeEventListener("hashchange", onHashChange)
26+
})
27+
28+
return {
29+
filterRef
30+
}
31+
}

0 commit comments

Comments
 (0)