@ v-bind:attr v-model v-html v-if v-show v-for="(item, index) in obj" :key="item.id" -- @keyup.enter
ref.value 改动 → 触发 $state 更新 → 页面刷新
reactive 局部改动 → 触发 $state 更新
reactive 整体改动 → 不会触发,要改就改具体属性
// 改响应式数据后马上要操作DOM
await nextTick()
// 非public目录下静态资源
const imgUrl = new URL("./logo.png", import.meta.url).href
// public目录下静态资源
const publicImg = "/logo.png"
// .env VITE_XXX
const apiBase = import.meta.env.VITE_API_BASE
onMounted(() => {})
onUnmounted(() => {})
// () => obj.attr / deep: true
watch(count, (newVal, oldVal) => {
console.log(newVal, oldVal)
})
const double = computed(() => count.value * 2)
const fullName = computed({
get() {
return first.value + last.value
},
set() {
console.log("更新了fullName")
}
})
// 插槽
<template>
<slot name="header">默认内容</slot>
</template>
<Child>
<template #header>插槽内容</template>
</Child>
// 父子通信 - props
<script setup>
import { toRefs } from "vue"
const props = defineProps({
message: String,
count: Number
})
// 解构会切断响应 toRefs 保持
const { message, count } = toRefs(props)
</script>
<Child message="你好" :count="123" />
// 子父通信 - emit
<script setup>
const emit = defineEmits(["event"])
emit("event", data)
</script>
<Child @event="backFunc" />
<script setup>
function backFunc(data) {
// data 子组件自动传递过来
}
</script>
import { debounce, throttle } from "lodash-es"
// 防抖
const debounceFunc = debounce(() => {
// 业务逻辑
}, 500)
// 节流
const throttleFunc = throttle(() => {
// 业务逻辑
}, 500)
// 取消
debounceFunc.cancel()
throttleFunc.cancel()
<router-link to="/path">跳转</router-link>
<router-view></router-view>
import { useRouter, useRoute } from "vue-router"
const router = useRouter()
const route = useRoute()
route.meta
route.path
route.params
route.query
// 跳转
router.push("/path?q=xx")
router.replace("/path?q=xx")
const routes = [
{
path: "path/:id?",
name: "name",
component: () => import("组件路径"), // 懒加载
children: [
{
path: "child", // 不用写/ 相对父path
name: "child",
component: () => import("@/views/Child.vue")
}
], // 嵌套子路由
meta: { key: "value" } // 元信息
}
]
router.beforeEach(async (to, from) => {
// 跳转前触发, return false 可取消跳转
// 常用来做登录校验、权限控制
})
router.afterEach(async (to, from) => {
// 跳转成功后触发
})
import { defineStore, storeToRefs } from "pinia"
// 放 main.ts
import piniaPluginPersistedstate from "pinia-plugin-persistedstate"
pinia.use(piniaPluginPersistedstate)
// 准备store
export const useXxxStore = defineStore("xxx", () => {
const object = "xxx"
const temp = "临时不持久化"
function func(args) {
// 行为
}
return { object }
}, {
persist: {
key: "my-custom-key",
storage: localStorage, // 可选 sessionStorage 注意 ref reactive 问题
paths: ["object"] // 不写该配置默认持久化所有变常量
}
})
import { useXxxStore, storeToRefs } from "./store"
const xxxStore = useXxxStore()
const { object } = storeToRefs(xxxStore)
// 或者直接访问 保持响应态
xxxStore.object