学习Vue3 第七章(认识Reactive全家桶)
生活随笔
收集整理的這篇文章主要介紹了
学习Vue3 第七章(认识Reactive全家桶)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
reactive
用來綁定復雜的數據類型 例如 對象 數組
reactive 源碼約束了我們的類型
他是不可以綁定普通的數據類型這樣是不允許 會給我們報錯
import { reactive} from 'vue'let person = reactive('sad')綁定普通的數據類型 我們可以 使用昨天講到ref
你如果用ref去綁定對象 或者 數組 等復雜的數據類型 我們看源碼里面其實也是 去調用reactive
使用reactive 去修改值無須.value
reactive 基礎用法
import { reactive } from 'vue' let person = reactive({name:"小滿" }) person.name = "大滿"數組異步賦值問題
這樣賦值頁面是不會變化的因為會脫離響應式
let person = reactive<number[]>([]) setTimeout(() => {person = [1, 2, 3]console.log(person);},1000)解決方案1
使用push
import { reactive } from 'vue' let person = reactive<number[]>([]) setTimeout(() => {const arr = [1, 2, 3]person.push(...arr)console.log(person);},1000)方案2
包裹一層對象
type Person = {list?:Array<number> } let person = reactive<Person>({list:[] }) setTimeout(() => {const arr = [1, 2, 3]person.list = arr;console.log(person);},1000)readonly
拷貝一份proxy對象將其設置為只讀
import { reactive ,readonly} from 'vue' const person = reactive({count:1}) const copy = readonly(person)//person.count++copy.count++shallowReactive?
只能對淺層的數據 如果是深層的數據只會改變值 不會改變視圖
案例
<template><div><div>{{ state }}</div><button @click="change1">test1</button><button @click="change2">test2</button></div> </template><script setup lang="ts"> import { shallowReactive } from 'vue'const obj = {a: 1,first: {b: 2,second: {c: 3}} }const state = shallowReactive(obj)function change1() {state.a = 7 } function change2() {state.first.b = 8state.first.second.c = 9console.log(state); }</script> <style> </style>總結
以上是生活随笔為你收集整理的学习Vue3 第七章(认识Reactive全家桶)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正版NOD32升级ID在线申请
- 下一篇: 防火墙小结