vue3 ref 和reactive的區(qū)別詳解
源碼分析視頻 點擊進入
Ref
ref數(shù)據(jù)響應式監(jiān)聽。ref 函數(shù)傳入一個值作為參數(shù),一般傳入基本數(shù)據(jù)類型,返回一個基于該值的響應式Ref對象,該對象中的值一旦被改變和訪問,都會被跟蹤到,就像我們改寫后的示例代碼一樣,通過修改 count.value 的值,可以觸發(fā)模板的重新渲染,顯示最新的值
<template>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<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是用來定義更加復雜的數(shù)據(jù)類型,但是定義后里面的變量取出來就不在是響應式Ref對象數(shù)據(jù)了
所以需要用toRefs函數(shù)轉化為響應式數(shù)據(jù)對象

將上面用ref寫的代碼轉化成reactive型的代碼
<template>
<!-- <img alt="Vue logo" src="./assets/logo.png"> -->
<div>
<h1>{{ name }}</h1>
<h1>{{ age }}</h1>
<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ū)別詳解的文章就介紹到這了,更多相關vue3 ref 和reactive 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Vue3.0中Ref與Reactive的區(qū)別示例詳析
- vue3?中ref和reactive的區(qū)別講解
- 前端vue3中的ref與reactive用法及區(qū)別總結
- Vue3 的ref和reactive的用法和區(qū)別示例解析
- Vue3中ref和reactive的基本使用及區(qū)別詳析
- Vue3中ref和reactive的區(qū)別及說明
- vue3.0中ref與reactive的區(qū)別及使用場景分析
- Vue3中關于ref和reactive的區(qū)別分析
- vue3中reactive和ref的實現(xiàn)與區(qū)別詳解
- vue3中ref和reactive的區(qū)別舉例詳解
相關文章
vue百度地圖通過地址名稱獲取地址的經(jīng)緯度gps問題(具體步驟)
在Vue項目中,可以通過使用百度地圖JavaScript?API來實現(xiàn)根據(jù)地址名稱獲取經(jīng)緯度GPS的功能,本文分步驟給大家詳細講解vue百度地圖獲取經(jīng)緯度的實例,感興趣的朋友一起看看吧2023-05-05
vue3+vite+ts使用require.context問題
這篇文章主要介紹了vue3+vite+ts使用require.context問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Vue基于iview table展示圖片實現(xiàn)點擊放大
這篇文章主要介紹了Vue基于iview table展示圖片實現(xiàn)點擊放大,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08

