vue3 ref 和reactive的區(qū)別詳解
源碼分析視頻 點(diǎn)擊進(jìn)入
Ref
ref數(shù)據(jù)響應(yīng)式監(jiān)聽(tīng)。ref 函數(shù)傳入一個(gè)值作為參數(shù),一般傳入基本數(shù)據(jù)類型,返回一個(gè)基于該值的響應(yīng)式Ref對(duì)象,該對(duì)象中的值一旦被改變和訪問(wèn),都會(huì)被跟蹤到,就像我們改寫(xiě)后的示例代碼一樣,通過(guò)修改 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是用來(lái)定義更加復(fù)雜的數(shù)據(jù)類型,但是定義后里面的變量取出來(lái)就不在是響應(yīng)式Ref對(duì)象數(shù)據(jù)了
所以需要用toRefs函數(shù)轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)對(duì)象
將上面用ref寫(xiě)的代碼轉(zhuǎn)化成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>
到此這篇關(guān)于vue3 ref 和reactive的區(qū)別詳解的文章就介紹到這了,更多相關(guān)vue3 ref 和reactive 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- vue3.0中ref與reactive的區(qū)別及使用場(chǎng)景分析
- Vue3中關(guān)于ref和reactive的區(qū)別分析
- 一步步從Vue3.x源碼上理解ref和reactive的區(qū)別
- Vue3響應(yīng)式方案及ref?reactive的區(qū)別詳解
- vue3?中ref和reactive的區(qū)別講解
- Vue3中ref和reactive的基本使用及區(qū)別詳析
- 淺談vue3中ref、toRef、toRefs?和?reactive的區(qū)別
- Vue3.0中Ref與Reactive的區(qū)別示例詳析
- Vue3 的ref和reactive的用法和區(qū)別示例解析
相關(guān)文章
Element-UI中關(guān)于table表格的那些騷操作(小結(jié))
這篇文章主要介紹了Element-UI中關(guān)于table表格的那些騷操作(小結(jié)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08vue router 跳轉(zhuǎn)后回到頂部的實(shí)例
今天小編就為大家分享一篇vue router 跳轉(zhuǎn)后回到頂部的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08