Vue3实践2
1.插槽
在 Vue 3 中,插槽(Slots)是一种功能,它允许你在组件的模板中预留一个或多个位置,这些位置可以被组件的使用者(即父组件)用自定义的模板替换。
1. 定义插槽
在子组件(被插入的组件)中,你可以使用 <slot>
标签来定义一个或多个插槽。你可以为插槽指定一个名称,也可以定义一个默认内容,当父组件没有提供相应的插槽内容时显示默认内容。
2. 使用插槽
在父组件中,当你插入子组件时,你可以使用 <template v-slot>
或简写 <template #slot>
来指定要插入的内容。如果插槽有名称,你可以使用 v-slot:slotName
来指定内容。
例如
子组件
<template><div class="my-component"><slot name="title">默认标题</slot><p>这是子组件的内容。</p></div>
</template>
父组件
<template><div><MyComponent><template #title><h2 class="section-header">最受欢迎</h2></template></MyComponent></div>
</template>
2.RouterLink
用于在 Vue.js 应用中创建导航链接
基本用法
<template><div><RouterLink to="/about">关于</RouterLink><RouterLink to="/contact">联系我们</RouterLink></div>
</template>
动态路由
<template><div><RouterLink :to="{ name: 'User', params: { id: 123 } }">用户 123</RouterLink></div>
</template>
或者
<RouterLink :to="{path:'/books/${props.book.id}',query: {author: props.book.author,title: props.book.title,cover: props.book.cover,detail: props.book.detail,type: props.book.type,content_url: props.book.content_url,publication_date: props.book.publication_date,publisher: props.book.publisher,}}" class="book-card">
接收参数
// 目标页面通过route.query获取
const bookId = useRoute().params.id; // 路径参数
const { author,type,content_url,cover,publication_date,publisher,title,detail} = useRoute().query; // 查询参数
路由配置的示例
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import home from '@/views/home.vue'
import bookInfo from '@/views/bookInfo.vue'
import bookRead from '@/views/bookRead.vue';
import bookCatalog from '../views/bookCatalog.vue';const routes = [{path: '/',name: 'home',component: home,},{path: '/books/:id',name: 'bookInfo',component: bookInfo,props: true,},{path: '/books/read/:id/:para',name: 'bookRead',component: bookRead,props: true,},{path: '/books/catalog/:id',name: 'bookCatalog',component: bookCatalog,props: true,}
]const router = createRouter({history: createWebHistory(),routes
})export default router;
在main.js中
const app = createApp(App);
app.use(router);
接收参数
// 目标页面通过route.query获取
const { id } = useRoute().params; // 路径参数
const { category, author } = useRoute().query; // 查询参数
3.响应式数据
响应式数据的定义
const arr=ref([])
当响应式数据更新时,DOM模板会自动响应数据的更新,值得注意的是,在javascript中获取响应式数据需要通过.value来获取但是在模板中不需要,因为vue3会自动帮我们解析
4.<nav>
<nav>
标签是 HTML5 中的语义化标签,用于定义页面中的导航区域。它通常包含导航链接,例如网站的主菜单、目录、分页链接等。
5.router.push()
通过 Vue Router 的 router.push
方法可以任意跳转路由
const router=useRouter();router.push({name:'next',query:{name:小明}
})
6.axios
关于axios,使用指南请看 起步 | Axios中文文档 | Axios中文网
首先安装 npm install axios
基本使用
await axios.get('http://ip:8088/library/novelChapter',{params:cur_params}).then((res) => {for(let i=0;i<res.data.data.length;i++){cur_content.push(res.data.data[i]);}}).catch((err)=>{console.log(err)});
其中第二个参数是请求参数
axios请求一般是异步的,有的时候需要注意同步
一般写法
async function postJournal(path: string, journal: any) {const res = await axios({method: "POST", // 注意是 method 不是 methonurl: address + path, // 注意是 url 不是 URLdata: journal // 这里传递参数});return res.data;
}
只在 POST/PUT/PATCH 这类有请求体的方法中使用,可以直接传递对象,axios 会自动把它转成 JSON 发送给后端。
如果是GET请求使用params
如:
await axios.get("http://localhost:8088/api/journal", {params: {province: "北京",author: "张三",page: 2,pageSize: 10}
});
6.vuex
import { createStore } from 'vuex';
createStore
是 Vuex 4 中用于创建一个新的 Vuex store 的函数。在 Vue 3 中,Vuex 4 是与 Vue 3 配合使用的状态管理库。
export default createStore({state: {globalVar: 'Hello, World!'},mutations: {setGlobalVar(state, value) {state.globalVar = value;}},actions: {updateGlobalVar({ commit }, value) {commit('setGlobalVar', value);}}
});
state
是 Vuex store 的核心部分,它是一个对象,用于存储全局状态。在这个例子中,state
包含一个属性 globalVar
,其初始值为 'Hello, World!'
。
mutations
是用于修改 state
的方法集合。在 Vuex 中,所有对 state
的修改都必须通过 mutations
来进行。mutations
方法的第一个参数是当前的 state
,第二个参数是传递给 mutations
的值。
actions
是用于触发 mutations
的方法集合。actions
可以包含异步逻辑,而 mutations
不能包含异步逻辑。actions
方法的第一个参数是一个上下文对象,包含 commit
方法,用于调用 mutations
。
在这个例子中,定义了一个 actions
方法 updateGlobalVar
,它调用了 mutations
中的 setGlobalVar
方法来更新 state.globalVar
。
在组件中的使用方法
导入useStore
import { useStore } from 'vuex'const store = useStore();
7.媒体查询
媒体查询是 CSS 中的一种功能,允许根据不同的设备特性(如屏幕宽度、屏幕方向等)应用不同的样式规则。它的基本语法是:
@media (条件) {/* 样式规则 */
}
8.Grid
CSS Grid 是一种强大的二维布局系统,允许开发者通过行和列来创建复杂的布局。这段代码中使用了以下 Grid 属性:
-
grid-template-columns
:定义网格的列布局。-
repeat(3, 1fr)
:表示创建 3 列,每列的宽度为1fr
(表示每列占据可用空间的等分)。 -
repeat(2, 1fr)
:表示创建 2 列,每列的宽度为1fr
。 -
1fr
:表示创建 1 列,占据整个可用宽度。
-
9.router.afterEach()
router.afterEach((to)=>{current.value = [to.path];
})
在路由跳转完成后的操作
10.reactive
在 Vue 3 中,reactive()
是一个函数,用于将普通对象转换为响应式对象,这在处理复杂状态时非常有用,特别是对象或数组类型。
reactive
函数接受一个对象作为参数,并返回一个响应式引用。这个响应式引用可以被 Vue 的模板或 Composition API 中的 watch
函数所使用,以观察对象的变化。
import { reactive } from 'vue';const state = reactive({count: 0
});// 使用 watch 来观察 state 的变化
import { watch } from 'vue';
watch(() => state.count, (newCount, prevCount) => {console.log(`count changed from ${prevCount} to ${newCount}`);
});
11.watch
在 Vue 3 中,watch
是一个强大的响应式 API,用于观察和响应 Vue 应用中数据的变化。你可以使用 watch
来观察响应式数据、普通数据、计算属性(computed properties)甚至是其他 watch
实例。
watch
函数接受两个参数:第一个是观察的目标,第二个是回调函数,该函数会在目标发生变化时被调用。
import { watch } from 'vue';setup() {const count = ref(0);watch(count, (newValue, oldValue) => {console.log(`count changed from ${oldValue} to ${newValue}`);});
}
12.ref
在 Vue 3 中,ref
是一个函数,它是响应式 API 的一部分,用于创建响应式引用。
ref
函数接受一个值作为参数,并返回一个响应式引用对象。这个对象有一个 .value
属性,它反映了原始值。
13.ref
和 reactive的区别
ref
函数用于创建一个响应式引用,它可以包含任何类型的值,包括原始类型(如字符串、数字、布尔值)和对象。ref
返回的对象有一个 .value
属性,用于访问和修改原始值。
reactive
函数用于将一个包含多个属性的对象转换为响应式对象。这在处理包含多个属性的对象时非常有用,因为它允许 Vue 追踪对象内部的每个属性的变化。
-
ref
用于创建单个值的响应式引用。 -
reactive
用于将对象转换为响应式对象,以便追踪对象内部属性的变化。
14.${}
在 Vue 组件的模板中,${}
用于访问组件实例的属性和方法。
<template><div>{{ $name }}</div><button @click="$greet">Greet</button>
</template><script setup>
import { ref } from 'vue';const name = ref('Alice');
const greet = () => {console.log(`Hello, ${name.value}!`);
};
</script>
15.JavaScript 日期处理库——date-fns
date-fns
是一个现代的 JavaScript 日期库,它提供了丰富的日期操作功能,包括日期的创建、解析、操作、格式化等。
npm install date-fns
import { format } from 'date-fns';const now = new Date();
const formattedDate = format(now, 'yyyy-MM-dd HH:mm:ss');
console.log(formattedDate); // 输出格式化后的日期字符串
date-fns
的 format
函数支持多种格式指令:
-
yyyy
:四位数的年份(例如:2024)。 -
MM
:两位数的月份(01 到 12)。 -
dd
:两位数的月份中的天(01 到 31)。 -
HHH
:两位数的小时(00 到 23)。 -
mm
:两位数的分钟(00 到 59)。 -
ss
:两位数的秒(00 到 59)。
16.路由守卫
在 Vue.js 框架中,路由守卫(Route Guards)是一种非常有用的功能,它允许你在路由跳转场(navigation)发生之前或之后执行逻辑。
-
全局前置守卫(Global Before Guards):
-
使用
router.beforeEach(to, from, next)
方法定义全局前置守卫,它对每个路由跳转场都会触发。 -
to
:目标路由对象。 -
from
:当前导航的路由对象。 -
next
:进行路由跳转场的函数。
-
-
全局后置守卫(Global After Guards):
-
使用
router.afterEach(to, from)
方法定义全局后置守卫,它在每个路由跳场完成后触发。
-
-
路由独享守卫(Per-route Guards):
-
可以在路由配置中使用
beforeEnter
和afterEnter
选项定义路由独享守卫。 -
例如,在路由配置中使用
beforeEnter: (to, from, next)
定义前置守卫。
-
-
组件内守卫(In-Component Guards):
-
可以在路由组件内部使用
beforeRouteEnter
、beforeRouteUpdate
和beforeRouteLeave
钩子定义守卫。 -
这些守卫可以访问
this
,这意味着可以访问组件实例和数据。
-
示例代码,全局前置路由守卫
const router = new VueRouter({// ...路由配置
});router.beforeEach((to, from, next) => {// 在这里编写前置守卫逻辑if (to.path === '/secret' && !user.isLoggedIn) {next({ path: '/login' });} else {next();}
});
17.v-model
-
双向数据绑定:
v-model
实现了数据的双向绑定,即:-
当用户在表单控件中输入或更改值时,绑定的数据会自动更新。
-
当绑定的数据发生变化时,表单控件的值也会自动更新。
-
<input v-model="message">