这几天写中期检查去了,断更了
01需求分析
- 点击首页搜索框,出现搜索页
- 点击搜索页,隐藏搜索页,展示首页
- 新建搜索页组件
知识点1:ref
和 reactive
都是创建响应式数据的方法
-
使用
ref
当:- 你处理的是基本数据类型(如字符串、数字或布尔值)。
- 你需要将响应式数据作为 prop 传递给子组件。
- 你需要在模板中直接引用响应式数据。
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value++;
};
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
-
使用
reactive
当:- 你处理的是复杂数据类型(如对象或数组)。
- 你希望以更自然的方式操作对象或数组。
- 你不需要跨组件传递整个响应式对象。
<script setup>
import { reactive } from 'vue';
const state = reactive({
newTask: '',
tasks: []
});
const addTask = () => {
if (state.newTask) {
state.tasks.push(state.newTask);
state.newTask = '';
}
};
const removeTask = (index) => {
state.tasks.splice(index, 1);
};
</script>
<template>
<div>
<input v-model="state.newTask" placeholder="Add a new task">
<button @click="addTask">Add Task</button>
<ul>
<li v-for="(task, index) in state.tasks" :key="index">
{{ task }}
<button @click="removeTask(index)">Remove</button>
</li>
</ul>
</div>
</template>
知识点2:hooks切换显示隐藏状态的
hook是用来管理页面状态的被提取到放在一个vue里面
现在我写的它的useToggle它作用是提供一个简单的开关功能,通常用于在两种状态(如显示和隐藏)之间切换
import { ref } from 'vue'
import type { Ref } from 'vue'
export function useToggle(initState: boolean): [Ref<boolean>, () => void] {
const state = ref(initState)
const toggle = function () {
state.value = !state.value
}
return [state, toggle]
}
// isSearchViewShown是一个响应式的布尔值,用于跟踪搜索视图是否显示,用于搜索页的切换
// 而toggleSearchView是一个函数,用于切换isSearchViewShown的值