溫馨提示×

溫馨提示×

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

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

vue3?ref和reactive的區(qū)別有哪些

發(fā)布時(shí)間:2023-03-17 10:16:35 來源:億速云 閱讀:102 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“vue3 ref和reactive的區(qū)別有哪些”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“vue3 ref和reactive的區(qū)別有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

Ref

ref數(shù)據(jù)響應(yīng)式監(jiān)聽。ref 函數(shù)傳入一個(gè)值作為參數(shù),一般傳入基本數(shù)據(jù)類型,返回一個(gè)基于該值的響應(yīng)式Ref對象,該對象中的值一旦被改變和訪問,都會(huì)被跟蹤到,就像我們改寫后的示例代碼一樣,通過修改 count.value 的值,可以觸發(fā)模板的重新渲染,顯示最新的值

<template>
  
  <h2>{{name}}</h2>
  <h2>{{age}}</h2>
  <button @click="sayName">按鈕</button>
</template>

<script lang="ts">
import {ref,computed} from 'vue' 

export default {
  name: 'App',
  setup(){
    const name = ref('zhangsan')
    const birthYear = ref(2000)
    const now = ref(2020)
    const age = computed(()=>{
      return now.value - birthYear.value
    })
    const sayName = () =>{
      name.value = 'I am ' + name.value
    }
    return {
      name,
      sayName,
      age
    }
  }
}
</script>

reactive

reactive是用來定義更加復(fù)雜的數(shù)據(jù)類型,但是定義后里面的變量取出來就不在是響應(yīng)式Ref對象數(shù)據(jù)了

所以需要用toRefs函數(shù)轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)對象

vue3?ref和reactive的區(qū)別有哪些

將上面用ref寫的代碼轉(zhuǎn)化成reactive型的代碼

<template>
  <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
  <div>
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
    <button @click="sayName">按鈕</button>
  </div>
</template>

<script lang="ts">
import { computed, reactive,toRefs } from "vue";

interface DataProps {
  name: string;
  now: number;
  birthYear: number;
  age: number;
  sayName: () => void;
}

export default {
  name: "App",
  setup() {
   

    const data: DataProps = reactive({
      name: "zhangsan",
      birthYear: 2000,
      now: 2020,
      sayName: () => {
        console.log(1111);
        console.log(data.name);
        
        data.name = "I am " + data.name;
        console.log(data.name);
      },
      age: computed(() => {
        return data.now - data.birthYear;
      }),
    });

    const refData = toRefs(data)
    refData.age
    return {
      ...refData,
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

讀到這里,這篇“vue3 ref和reactive的區(qū)別有哪些”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

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

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

AI