
image.png
特殊文件夾說明:
- types 定義一些Typescript 數(shù)據(jù)約束
- use 組合是函數(shù)的統(tǒng)一管理 ,文件名默認以use開頭
Vue3一些新特性
-
Composition API
- 創(chuàng)建響應式對象的方式: ref 、toRef、toRefs、reactive
- ref() 函數(shù)根據(jù)給定的值創(chuàng)建一個響應式的數(shù)據(jù)對象,傳入的為基本數(shù)據(jù)類型,例如字符串、數(shù)字、boolean 等,返回值是一個對象,這個對象上只包含一個 value 屬性,只在setup函數(shù)內(nèi)部訪問ref函數(shù)需要加.value
- reactive 方法 根據(jù)傳入的對象 ,創(chuàng)建返回一個深度響應式對象
- 針對一個響應式對象(reactive 封裝)的 prop(屬性)創(chuàng)建一個ref,且保持響應式
- toRefs 是一種用于破壞響應式對象并將其所有屬性轉(zhuǎn)換為 ref 的實用方法
import {ref, reactive, toRef, toRefs} from 'vue'; export default { name:'App' setup(){ let stringRef = ref(""); let obj = {name : 'alice', age : 12}; let reactiveRef = reactive(obj) let objNameToRef= toRef(obj, 'name'); let objToRefs = toRefs(reactiveRef ) return {stringRef ,reactiveRef ,objNameToRef,...objToRefs } } } - 創(chuàng)建響應式對象的方式: ref 、toRef、toRefs、reactive
watchEffect && watch 區(qū)別
1.watch可以訪問新值和舊值,watchEffect不能訪問。
2.watchEffect有副作用,DOM掛載或者更新之前就會觸發(fā),需要我們自己去清除副作用。
3.watch是惰性執(zhí)行,也就是只有監(jiān)聽的值發(fā)生變化的時候才會執(zhí)行,但是watchEffect不同,每次代碼加載watchEffect都會執(zhí)行。
4.watch需要指明監(jiān)聽的對象,也需要指明監(jiān)聽的回調(diào)。watchEffect會立即執(zhí)行傳入的一個函數(shù),同時響應式追蹤其依賴,并在其依賴變更時重新運行該函數(shù)。
import {ref, reactive, toRef, toRefs} from 'vue';
export default {
name:'App'
setup(){
let obj = {name : 'alice', age : 12};
let reactiveRef = reactive(obj)
watch(()=>reactiveRef .name,(old,newVal)=>{},{deep:true})
watch([()=>reactiveRef .name,()=>reactiveRef.age],(old,newVal)=>{},{deep:true})
}
}
- 組合式函數(shù)
https://cn.vuejs.org/guide/reusability/composables.html#mouse-tracker-example
“組合式函數(shù)”(Composables) 是一個利用 Vue 的組合式 API 來封裝和復用有狀態(tài)邏輯的函數(shù)。
import type { UnwrapRef,Ref } from 'vue'
import { ref } from 'vue'
#useLoading.js
export function useLoading(initState: boolean): [Ref<boolean>, () => void] {
const state = ref(initState)
const toggleLoading = function () {
state.value = !state.value
}
return [state, toggleLoading]
}
#useAsync.js
export function useAsync<T>(asyncFn: () => Promise<T>, initValue: T, immediate = true) {
const [toggleLoading] = useLoading(false)
const data = ref(initValue)
const error = ref(null)
const execute = function () {
toggleLoading()
error.value = null
return asyncFn()
.then((res) => {
data.value = res as UnwrapRef<T>
toggleLoading()
})
.catch((err) => {
error.value = err
toggleLoading()
})
}
if (immediate) {
execute()
}
return {
pending,
data,
error,
execute,
}
}
UnwrapRef<T>類型,就是對Ref類型就行反解
- 內(nèi)置組件Teleport
<Teleport> 是一個內(nèi)置組件,它可以將一個組件內(nèi)部的一部分模板“傳送”到該組件的 DOM 結(jié)構(gòu)外層的位置去。
<template>
<button @click="open = true">Open Modal</button>
<Teleport to="body">
<div v-if="open" class="modal">
<p>modal將會被插入到body下面</p>
<button @click="open = false">Close</button>
</div>
</Teleport>
</template>
- 異步組件
vue2
const asyncPage = () => import('./Lazy.vue')
https://cn.vuejs.org/guide/components/async.html#loading-and-error-states
Vue3
<script>
import { defineAsyncComponent } from 'vue'
export default {
components: {
AdminPage: defineAsyncComponent(() =>
import('./components/AdminPageComponent.vue')
)
}
}
</script>
<template>
<AdminPage />
</template>
Typescript在Vue3中的一些用法
- 自定義事件、屬性 defineEmits、defineProps
<script setup lang="ts">
import { defineProps, defineEmits } from 'vue'
interface IProps {
showAction?: boolean
background?: string
placeholder?: string
shape?: string
modelValue?: string | number
}
const props = defineProps<IProps>()
interface IEmits {
(e: 'search', v?: string | number): void
(e: 'cancel'): void
(e: 'clear'): void
(e: 'update:modelValue', v?: string | number): void
(e: 'inputClick'): void
}
const emits = defineEmits<IEmits>()
const onKeypress = (e: KeyboardEvent) => {
const ENTER_CODE = 13
if (e.keyCode === ENTER_CODE) {
e.preventDefault()
emits('search', props.modelValue)
}
}
const onClear = () => {
emits('update:modelValue', '')
emits('clear')
}
</script>
<template>
<input
type="search"
class="op-field__control"
:value="modelValue"
:placeholder="placeholder"
@keypress="onKeypress"
@click="emits('inputClick')"
@input="(e) => emits('update:modelValue', (e.target as HTMLInputElement).value)"
/>
</template>
Pinia用法
- defineStore定義倉庫
import {defineStore} from "pinia";
export const userStore = defineStore('user',{
state:()=>{return{
name:""
}},
getters:{},
actions:{
updateUser(name){
this.name = name
}
}
})
- storeToRefs()讀取state
import {storeToRefs} from 'pinia'
let user = userStore()
const {name} = storeToRefs(user)
- patch 函數(shù)修改state
- Action通過函數(shù)更改state
- store 的 $reset() 方法將 state 重置為初始值。
- 通過 store 的 $subscribe() 方法偵聽 state 及其變化
cartStore.$subscribe((mutation, state) => {
// import { MutationType } from 'pinia'
mutation.type // 'direct' | 'patch object' | 'patch function'
// 和 cartStore.$id 一樣
mutation.storeId // 'cart'
// 只有 mutation.type === 'patch object'的情況下才可用
mutation.payload // 傳遞給 cartStore.$patch() 的補丁對象。
// 每當狀態(tài)發(fā)生變化時,將整個 state 持久化到本地存儲。
localStorage.setItem('cart', JSON.stringify(state))
})
問題:類型“ImportMeta”上不存在屬性“env”。
在 tsconfig.json 文件中添加如下配置即可
“types”: [ “vite/client” ]