溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

vue3中常用的API如何使用

發(fā)布時(shí)間:2021-03-26 11:28:29 來(lái)源:億速云 閱讀:281 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了vue3中常用的API如何使用,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

vue3.x已經(jīng)發(fā)布了這么久,相關(guān)的生態(tài)也慢慢起來(lái)了,包括vite這個(gè)新的打包工具,在vue3.0學(xué)習(xí)過(guò)程中有一些實(shí)用性的api對(duì)比,希望能在開(kāi)發(fā)中給大家做個(gè)示范,準(zhǔn)確的使用對(duì)應(yīng)的api去完成我們的項(xiàng)目開(kāi)發(fā)

生命周期的變更

要特別說(shuō)明一下的就是,setup 函數(shù)代替了 beforeCreate 和 created 兩個(gè)生命周期函數(shù),因此我們可以認(rèn)為它的執(zhí)行時(shí)間在beforeCreate 和 created 之間

Vue2Vue3
beforeCreatesetup
createdsetup
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestoryonBeforeUnmount
destoryedonUnmounted

了解過(guò)vue3的小伙伴兒都知道,現(xiàn)在使用都會(huì)用到setup函數(shù),關(guān)于在setup函數(shù)操作數(shù)據(jù),我們用例子說(shuō)明會(huì)好一點(diǎn)

reactive

reactive 方法是用來(lái)創(chuàng)建一個(gè)響應(yīng)式的數(shù)據(jù)對(duì)象,該API也很好地解決了Vue2通過(guò) defineProperty 實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式的缺陷

用法很簡(jiǎn)單,只需將數(shù)據(jù)作為參數(shù)傳入即可

<template>
 <div id="app">
 <!-- 4. 訪問(wèn)響應(yīng)式數(shù)據(jù)對(duì)象中的 count -->
 {{ state.count }}
 </div>
</template>

<script>
// 1. 從 vue 中導(dǎo)入 reactive 
import {reactive} from 'vue'
export default {
 name: 'App',
 setup() {
 // 2. 創(chuàng)建響應(yīng)式的數(shù)據(jù)對(duì)象
 const state = reactive({count: 3})

 // 3. 將響應(yīng)式數(shù)據(jù)對(duì)象state return 出去,供template使用
 return {state}
 }
}
</script>

ref

在介紹 setup 函數(shù)時(shí),我們使用了 ref 函數(shù)包裝了一個(gè)響應(yīng)式的數(shù)據(jù)對(duì)象,這里表面上看上去跟 reactive 好像功能一模一樣啊,確實(shí)差不多,因?yàn)?ref 就是通過(guò) reactive 包裝了一個(gè)對(duì)象 ,然后是將值傳給該對(duì)象中的 value 屬性,這也就解釋了為什么每次訪問(wèn)時(shí)我們都需要加上 .value

我們可以簡(jiǎn)單地把 ref(obj) 理解為這個(gè)樣子 reactive({value: obj})

<script>
import {ref, reactive} from 'vue'
export default {
 name: 'App',
 setup() {
 const obj = {count: 3}
 const state1 = ref(obj)
 const state2 = reactive(obj)

 console.log(state1)
 console.log(state2)
 }
 
}
</script>

vue3中常用的API如何使用

注意: 這里指的 .value 是在 setup 函數(shù)中訪問(wèn) ref 包裝后的對(duì)象時(shí)才需要加的,在 template 模板中訪問(wèn)時(shí)是不需要的,因?yàn)樵诰幾g時(shí),會(huì)自動(dòng)識(shí)別其是否為 ref 包裝過(guò)的

那么我們到底該如何選擇 ref 和 reactive 呢?
建議:

  1. 基本類(lèi)型值(String 、Nmuber 、Boolean 等)或單值對(duì)象(類(lèi)似像 {count: 3} 這樣只有一個(gè)屬性值的對(duì)象)使用 ref

  2. 引用類(lèi)型值(Object 、Array)使用 reactive

我們?cè)趘ue2.x中獲取元素標(biāo)簽是用 ref ,vue3.x我們要獲取元素標(biāo)簽怎么辦呢?

<template>
 <div>
 <div ref="el">div元素</div>
 </div>
</template>

<script>
import { ref, onMounted } from 'vue'
export default {
 setup() {
 // 創(chuàng)建一個(gè)DOM引用,名稱(chēng)必須與元素的ref屬性名相同
 const el = ref(null)

 // 在掛載后才能通過(guò) el 獲取到目標(biāo)元素
 onMounted(() => {
  el.value.innerHTML = '內(nèi)容被修改'
 })

 // 把創(chuàng)建的引用 return 出去
 return {el}
 }
}
</script>

獲取元素的操作一共分為以下幾個(gè)步驟:

  1. 先給目標(biāo)元素的 ref 屬性設(shè)置一個(gè)值,假設(shè)為 el

  2. 然后在 setup 函數(shù)中調(diào)用 ref 函數(shù),值為 null,并賦值給變量 el,這里要注意,該變量名必須與我們給元素設(shè)置的 ref 屬性名相同

  3. 把對(duì)元素的引用變量 el 返回(return)出去

補(bǔ)充:設(shè)置的元素引用變量只有在組件掛載后才能訪問(wèn)到,因此在掛載前對(duì)元素進(jìn)行操作都是無(wú)效的
當(dāng)然如果我們引用的是一個(gè)組件元素,那么獲得的將是該組件的實(shí)例對(duì)象

toRef

toRef 是將某個(gè)對(duì)象中的某個(gè)值轉(zhuǎn)化為響應(yīng)式數(shù)據(jù),其接收兩個(gè)參數(shù),第一個(gè)參數(shù)為 obj 對(duì)象;第二個(gè)參數(shù)為對(duì)象中的屬性名

<script>
// 1. 導(dǎo)入 toRef
import {toRef} from 'vue'
export default {
 setup() {
  const obj = {count: 3}
  // 2. 將 obj 對(duì)象中屬性count的值轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)
  const state = toRef(obj, 'count')
 
  // 3. 將toRef包裝過(guò)的數(shù)據(jù)對(duì)象返回供template使用
  return {state}
 }
}
</script>

上面又有個(gè)ref,又有個(gè)toRef,不是沖突了嗎??jī)蓚€(gè)有不一樣的功效:

<template>
 <p>{{ state1 }}</p>
 <button @click="add1">增加</button>

 <p>{{ state2 }}</p>
 <button @click="add2">增加</button>
</template>

<script>
import {ref, toRef} from 'vue'
export default {
 setup() {
  const obj = {count: 3}
  const state1 = ref(obj.count)
  const state2 = toRef(obj, 'count')

  function add1() {
   state1.value ++
   console.log('原始值:', obj);
   console.log('響應(yīng)式數(shù)據(jù)對(duì)象:', state1);
  }

  function add2() {
   state2.value ++
   console.log('原始值:', obj);
   console.log('響應(yīng)式數(shù)據(jù)對(duì)象:', state2);
  }

  return {state1, state2, add1, add2}
 }
}
</script>

ref 是對(duì)原數(shù)據(jù)的一個(gè)拷貝,不會(huì)影響到原始值,同時(shí)響應(yīng)式數(shù)據(jù)對(duì)象值改變后會(huì)同步更新視圖
toRef 是對(duì)原數(shù)據(jù)的一個(gè)引用,會(huì)影響到原始值,但是響應(yīng)式數(shù)據(jù)對(duì)象值改變后會(huì)不會(huì)更新視圖

toRefs

將傳入的對(duì)象里所有的屬性的值都轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)對(duì)象,該函數(shù)支持一個(gè)參數(shù),即 obj 對(duì)象

<script>
// 1. 導(dǎo)入 toRefs
import {toRefs} from 'vue'
export default {
 setup() {
  const obj = {
   name: '前端印象',
   age: 22,
   gender: 0
  }
  // 2. 將 obj 對(duì)象中屬性count的值轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)
  const state = toRefs(obj)
 
  // 3. 打印查看一下
  console.log(state)
 }
}
</script>

返回的是一個(gè)對(duì)象,對(duì)象里包含了每一個(gè)包裝過(guò)后的響應(yīng)式數(shù)據(jù)對(duì)象

shallowReactive

聽(tīng)這個(gè)API的名稱(chēng)就知道,這是一個(gè)淺層的 reactive,難道意思就是原本的 reactive 是深層的唄,沒(méi)錯(cuò),這是一個(gè)用于性能優(yōu)化的API

<script>
<template>
 <p>{{ state.a }}</p>
 <p>{{ state.first.b }}</p>
 <p>{{ state.first.second.c }}</p>
 <button @click="change1">改變1</button>
 <button @click="change2">改變2</button>
</template>
<script>
import {shallowReactive} from 'vue'
export default {
 setup() {
  const obj = {
   a: 1,
   first: {
   b: 2,
   second: {
    c: 3
   }
   }
  }
  
  const state = shallowReactive(obj)
 
  function change1() {
   state.a = 7
  }

  function change2() {
   state.first.b = 8
   state.first.second.c = 9
   console.log(state);
  }

  return {state}
 }
}
</script>

首先我們點(diǎn)擊了第二個(gè)按鈕,改變了第二層的 b 和第三層的 c,雖然值發(fā)生了改變,但是視圖卻沒(méi)有進(jìn)行更新;

當(dāng)我們點(diǎn)擊了第一個(gè)按鈕,改變了第一層的 a 時(shí),整個(gè)視圖進(jìn)行了更新;

由此可說(shuō)明,shallowReactive 監(jiān)聽(tīng)了第一層屬性的值,一旦發(fā)生改變,則更新視圖

shallowRef

這是一個(gè)淺層的 ref,與 shallowReactive 一樣是拿來(lái)做性能優(yōu)化的,配合triggerRef ,調(diào)用它就可以立馬更新視圖,其接收一個(gè)參數(shù) state ,即需要更新的 ref 對(duì)象

shallowReactive 是監(jiān)聽(tīng)對(duì)象第一層的數(shù)據(jù)變化用于驅(qū)動(dòng)視圖更新,那么 shallowRef 則是監(jiān)聽(tīng) .value 的值的變化來(lái)更新視圖的

<template>
 <p>{{ state.a }}</p>
 <p>{{ state.first.b }}</p>
 <p>{{ state.first.second.c }}</p>
 <button @click="change">改變</button>
</template>

<script>
import {shallowRef, triggerRef} from 'vue'
export default {
 setup() {
  const obj = {
   a: 1,
   first: {
   b: 2,
   second: {
    c: 3
   }
   }
  }
  
  const state = shallowRef(obj)
  console.log(state);

  function change() {
   state.value.first.b = 8
   state.value.first.second.c = 9
   // 修改值后立即驅(qū)動(dòng)視圖更新
   triggerRef(state)
   console.log(state);
  }

  return {state, change}
 }
}
</script>

toRaw

toRaw 方法是用于獲取 ref 或 reactive 對(duì)象的原始數(shù)據(jù)的

<script>
import {reactive, toRaw} from 'vue'
export default {
 setup() {
  const obj = {
   name: '前端印象',
   age: 22
  }

  const state = reactive(obj) 
  const raw = toRaw(state)

  console.log(obj === raw) // true
 }
}
</script>

上述代碼就證明了 toRaw 方法從 reactive 對(duì)象中獲取到的是原始數(shù)據(jù),因此我們就可以很方便的通過(guò)修改原始數(shù)據(jù)的值而不更新視圖來(lái)做一些性能優(yōu)化了

注意: 補(bǔ)充一句,當(dāng) toRaw 方法接收的參數(shù)是 ref 對(duì)象時(shí),需要加上 .value 才能獲取到原始數(shù)據(jù)對(duì)象

markRaw

markRaw 方法可以將原始數(shù)據(jù)標(biāo)記為非響應(yīng)式的,即使用 ref 或 reactive 將其包裝,仍無(wú)法實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式,其接收一個(gè)參數(shù),即原始數(shù)據(jù),并返回被標(biāo)記后的數(shù)據(jù)。即使我們修改了值也不會(huì)更新視圖了,即沒(méi)有實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式

<template>
 <p>{{ state.name }}</p>
 <p>{{ state.age }}</p>
 <button @click="change">改變</button>
</template>

<script>
import {reactive, markRaw} from 'vue'
export default {
 setup() {
  const obj = {
   name: '前端印象',
   age: 22
  }
  // 通過(guò)markRaw標(biāo)記原始數(shù)據(jù)obj, 使其數(shù)據(jù)更新不再被追蹤
  const raw = markRaw(obj) 
  // 試圖用reactive包裝raw, 使其變成響應(yīng)式數(shù)據(jù)
  const state = reactive(raw) 

  function change() {
   state.age = 90
   console.log(state);
  }

  return {state, change}
 }
}
</script>

watchEffect

watchEffect 它與 watch 的區(qū)別主要有以下幾點(diǎn):

  1. 不需要手動(dòng)傳入依賴(lài)

  2. 每次初始化時(shí)會(huì)執(zhí)行一次回調(diào)函數(shù)來(lái)自動(dòng)獲取依賴(lài)

  3. 無(wú)法獲取到原值,只能得到變化后的值 

<script>
import {reactive, watchEffect} from 'vue'
export default {
 setup() { 
   const state = reactive({ count: 0, name: 'zs' })

   watchEffect(() => {
   console.log(state.count)
   console.log(state.name)
   /* 初始化時(shí)打?。?
     0
     zs

   1秒后打印:
     1
     ls
   */
   })

   setTimeout(() => {
   state.count ++
   state.name = 'ls'
   }, 1000)
 }
}
</script>

沒(méi)有像 watch 方法一樣先給其傳入一個(gè)依賴(lài),而是直接指定了一個(gè)回調(diào)函數(shù)

當(dāng)組件初始化時(shí),將該回調(diào)函數(shù)執(zhí)行一次,自動(dòng)獲取到需要檢測(cè)的數(shù)據(jù)是 state.count 和 state.name

根據(jù)以上特征,我們可以自行選擇使用哪一個(gè)監(jiān)聽(tīng)器

getCurrentInstance

我們都知道在Vue2的任何一個(gè)組件中想要獲取當(dāng)前組件的實(shí)例可以通過(guò) this 來(lái)得到,而在Vue3中我們大量的代碼都在 setup 函數(shù)中運(yùn)行,并且在該函數(shù)中 this 指向的是undefined,那么該如何獲取到當(dāng)前組件的實(shí)例呢?這時(shí)可以用到另一個(gè)方法,即 getCurrentInstance

<template>
 <p>{{ num }}</p>
</template>
<script>
import {ref, getCurrentInstance} from 'vue'
export default {
 setup() { 
  const num = ref(3)
  const instance = getCurrentInstance()
  console.log(instance)

  return {num}
 }
}
</script>

instance 中重點(diǎn)關(guān)注 ctx 和 proxy 屬性,這兩個(gè)才是我們想要的 this。可以看到 ctx 和 proxy 的內(nèi)容十分類(lèi)似,只是后者相對(duì)于前者外部包裝了一層 proxy,由此可說(shuō)明 proxy 是響應(yīng)式的

useStore

在Vue2中使用 Vuex,我們都是通過(guò) this.$store 來(lái)與獲取到Vuex實(shí)例,但上一部分說(shuō)了原本Vue2中的 this 的獲取方式不一樣了,并且我們?cè)赩ue3的 getCurrentInstance().ctx 中也沒(méi)有發(fā)現(xiàn) $store 這個(gè)屬性,那么如何獲取到Vuex實(shí)例呢?這就要通過(guò) vuex 中的一個(gè)方法了,即 useStore

// store 文件夾下的 index.js
import Vuex from 'vuex'

const store = Vuex.createStore({
 state: {
  name: '前端印象',
  age: 22
 },
 mutations: {
  ……
 },
 ……
})

// example.vue
<script>
// 從 vuex 中導(dǎo)入 useStore 方法
import {useStore} from 'vuex'
export default {
 setup() { 
  // 獲取 vuex 實(shí)例
  const store = useStore()

  console.log(store)
 }
}
</script>

然后接下來(lái)就可以像之前一樣正常使用 vuex 了

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“vue3中常用的API如何使用”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI