1. 程式人生 > 程式設計 >Vue3中reactive函式toRef函式ref函式簡介

Vue3中reactive函式toRef函式ref函式簡介

目錄
  • reactive函式
    • 用法:
  • toRef函式(瞭解即可)
    • 用法:
  • ref函式
    • 定義響應式資料
    • 直接定義使用
    • 獲取dom
    • 獲取元件例項物件

reactive函式

reactive用於定義響應式資料(可以理解 成data的替代品)www.cppcns.com

用法:

匯入 import {reactive} from ‘'

使用:

const state=reactive({
    引數名:引數值
})

訪問: state.引數名

訪問: state.引數名

toRef函式(瞭解即可)

toRef:將響應式資料中某個欄位提取出來成單獨響應式資料

用法:

匯入 import {toRef} from ‘vue'

使用:

const state=reactive({
    num:0
})
const num=toRef(state(響應式資料),'num屬性名')
num:{
    value:0
}
Rhttp://www.cppcns.comef實際可www.cppcns.com以理解成一種資料型別:{value:值}

訪問:num.value===0

注意點:

html:中使用響應式資料時可以不用寫value

中一定要寫value

ref函式

定義響應式資料

{
    value:值
}

直接定義使用

匯入
import {ref} from 'vue'
setup(){
定義
    const num=ref({a:1,b:2})  
    num:{
       value:{a:1,b:2}
    }
}

訪問: num.value===0

reactive:適用於多個數據,ref適用於單個數據

獲取dom

<template>
  <div ref="target">123</div>
</template>
scripte
import {ref} from 'vue'
setup(){
   const target=ref(null)   
   return {target} 
   target.value就是相應dom   
}

獲取元件例項物件

ref用於原生標籤就是獲取dom

ref用於元件標籤就是獲取元件例項物件

用法和獲取dom一樣的

<template>
  <元件標籤 ref="target">123</元件標籤>
</template>
script
import {ref} from 'vue'
setup(){
   const target=ref(null)   
   return {target} 
   target.value就是元件例項物件
}

以上就是Vue3中reactive函式toRef函式ref函式簡介的詳細內容,更多關於Vue3函式的資料請關注我們其它相關文章!