课程进度 92% · 第19/20章第19/20章 · 标签 1/3
— 1 —
组件复用
混入mixin:
javascript
1
// 混入:复用逻辑
2
// mixin.js
3
export default {
4
data() { return { msg: 'hello' } },
5
created() { console.log('混入生命周期') }
6
}
7
// 组件中使用
8
import mixin from './mixin.js'
9
export default { mixins: [mixin] }
10
}
组合式API与插件:
html
1
<!-- 组合式API:逻辑复用更灵活 -->
2
<script setup>
3
import { ref, onMounted } from 'vue'
4
function useCounter() {
5
const n = ref(0)
6
const inc = () => n.value++
7
return { n, inc }
8
}
9
const { n, inc } = useCounter()
10
onMounted(() => inc())
11
</script>
12
<!-- 插件注册 -->
13
import { createApp } from 'vue'
14
import MyPlugin from './plugin'
15
createApp(App).use(MyPlugin)
性能优化
- v-memo:条件缓存静态内容。
- v-once:只渲染一次。
- defineAsyncComponent:异步组件。
- 虚拟滚动:提升长列表性能。
html
1
<!-- 异步组件 -->
2
<script setup>
3
import { defineAsyncComponent } from 'vue'
4
const AsyncComp = defineAsyncComponent(() => import('./Comp.vue'))
5
</script>
6
<template>
7
<Suspense><AsyncComp /></Suspense>
8
</template>
9
<!-- v-memo缓存静态内容 -->
10
<div v-memo="[a, b]">静态内容</div>
11
<!-- v-once只渲染一次 -->
12
<div v-once>只渲染一次</div>
13
<!-- 虚拟滚动,需第三方库如vue-virtual-scroller -->
14
<virtual-list :size="40" :remain="10" :bench="5" :item="item" :item-count="1000" />
— 2 —
状态管理
Pinia与Vuex原理:
javascript
1
// Pinia用法
2
import { defineStore } from 'pinia'
3
export const useCounter = defineStore('counter', {
4
state: () => ({ n: 0 }),
5
actions: { inc() { this.n++ } }
6
})
7
// 组件中使用
8
const counter = useCounter()
9
counter.inc()
10
// Vuex原理:集中式状态管理,mutation驱动变更
provide/inject进阶:
html
1
<!-- provide/inject可传递响应式对象,实现全局共享 -->
2
<script setup>
3
import { provide, inject, reactive } from 'vue'
4
const theme = reactive({ color: 'red' })
5
provide('theme', theme)
6
const t = inject('theme')
7
</script>
路由与动态加载
vue-router基本用法:
javascript
1
import { createRouter, createWebHistory } from 'vue-router'
2
const routes = [
3
{ path: '/a', component: A },
4
{ path: '/b', component: B }
5
]
6
const router = createRouter({ history: createWebHistory(), routes })
7
// App.vue中
8
<router-link to="/a">A</router-link>
9
<router-view />
路由懒加载与导航守卫:
javascript
1
// 路由懒加载
2
const routes = [
3
{ path: '/a', component: () => import('./A.vue') }
4
]
5
// 导航守卫
6
router.beforeEach((to, from, next) => {
7
if (to.meta.auth && !isLogin()) next('/login')
8
else next()
9
})
组合式APIPinia异步组件路由懒加载