Skip to content

Vue 3:watch / watchEffect、Suspense、Teleport、指令与 Vue Router 4

一、watch 与 watchEffect

watchwatchEffect
监听源显式指定自动追踪回调内用到的响应式数据
首次执行默认惰性(可 immediate立即执行一次
新旧值可取 old/new不直接提供 old
典型场景精准监听某字段、异步请求快速原型、依赖关系简单

总结:要精确控制用 watch;要省事自动追踪用 watchEffect


二、Suspense

用于协调 异步组件async setup 的依赖;在就绪前展示 #fallback,就绪后渲染 #default

要点:#default 内应是 异步依赖组件defineAsyncComponent 或顶层 await)。


三、Teleport

把插槽内容渲染到 任意 DOM 节点(常用 body),解决遮罩被父级 overflow / transform / z-index 影响的问题。

html
<Teleport to="body">
  <div class="modal">...</div>
</Teleport>

四、自定义指令

全局

app.directive('name', { mounted, updated, ... })

局部 <script setup>

js
const vFocus = { mounted(el) { el.focus() } }

钩子(Vue 3)

beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted(名称较 Vue 2 对齐 DOM 生命周期)。

参数:elbindingvalueargmodifiers)、vnode / prevVnode


五、Vue Router 4

创建路由

  • new VueRoutercreateRouter
  • mode: 'history'history: createWebHistory()(或 createWebHashHistory

组合式 API

  • useRouter():编程式导航。
  • useRoute():当前路由对象。

组件内守卫映射

  • beforeRouteLeaveonBeforeRouteLeave
  • beforeRouteUpdateonBeforeRouteUpdate

需在 setup / <script setup> 中调用。

beforeRouteEnter:仅在选项式 API中作为组件选项使用(进入前、实例尚未创建);组合式 API 没有与之对称的 onBeforeRouteEnter。进入前鉴权可改用 beforeEnter(路由独享)全局 beforeEach,或在父级路由 / meta + 全局守卫 中处理(详见 Vue Router — Navigation Guards 中的 Full Navigation Resolution Flow)。


六、小结

  • watch 家族:精准 vs 自动追踪。
  • Suspense / Teleport:异步 UX 与层级解放。
  • 指令:DOM 横切。
  • Router 4createRouter + composable 风格导航守卫。

下一章:虚拟 DOM·diff·优化