Zu den verfügbaren Reactive-APIs gehören Reactive, ShallowReactive und die reaktive API, mit der die Ansicht reaktionsschnell aktualisiert werden kann. Die ShallowReactive-API aktualisiert die Ansicht flach. plus schreibgeschützte API
Reaktiv
Aus Vue exportieren, das Objekt mit reaktivem {Name: beautiful} umschließen
<template>
<div>
{
{person.name}}
</div>
</template>
<script setup lang='ts'>
// <!-- rective 不可以绑定普通类型 -->
import {
reactive} from 'vue'
let person=reactive({
name:'大漂亮'
})
person.name="小漂亮"
</script>
flachReaktiv
In der Ansicht wird nur die flache Ebene aktualisiert, die Daten werden jedoch aktualisiert
Beispiel 1
<template>
<div v-for="index in person">
<div>{
{index}}</div>
</div>
<button @click="add">数组加一</button>
</template>
import {
shallowReactive } from 'vue'
let person=shallowReactive<number[]>([])
const arr=[1,2,3];
person.push(...arr);
function add(){
console.log(person);
for(let i=0;i<person.length;i++){
console.log(person[i]++)
}
}
Ergebnis: Klicken Sie auf die Schaltfläche, der Wert im Personen-Array wird um eins erhöht und die Ansicht wird synchron aktualisiert
Beispiel 2
<template>
<div>
<div>{
{ state }}</div>
<button @click="change1">test1</button>
<button @click="change2">test2</button>
</div>
</template>
<script setup lang='ts'>
// <!-- rective 不可以绑定普通类型 -->
import {
reactive} from 'vue'
//只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图
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 = 8
state.first.second.c = 9
console.log(state);
}
</script>
Ergebnis:
Die ursprüngliche Anzeige der Seite
{ „a“: 1, „first“: { „b“: 2, „second“: { „c“: 3 } } } Klicken Sie auf Text1 und das Anzeigeergebnis ist: { „a ”: 7
,
„ first“: { „b“: 2, „second“: { „c“: 3 } } }
click text2 view result is
{ „a“: 7, „first“: { „b“: 2 , „second“: { „c“: 3 } } }
Die Konsolenausgabe lautet:
{ „a“: 7, „first“: { „b“: 8, „second“: { „c“: 9 } } } Daher werden durch die Verwendung von „shallowReactive“ tiefe Daten aktualisiert, jedoch nicht in der Ansicht aktualisiert. Wenn Sie den Code ändern in
<script>
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 = 8
state.first.second.c = 9
console.log(state);
}
</script>
Das Ergebnis des Klickens auf die Ansicht „test1“ ist { „a“: 7, „first“: { „b“: 2, „second“: { „c“: 3 } } } Das Ergebnis des Klickens auf die Ansicht „test2“ ist { „a“: 7, „first
“ „: { „b“: 8, „second“: { „c“: 9 } } }
Es ist ersichtlich, dass reactive alle Ansichten aktualisiert.
Beispiel für die schreibgeschützte Verwendung
import {
readonly} from 'vue'
const person = reactive({
count:1})
const copy = readonly(person)
person.count++
// copy.count++ 直接报错
Es kann in der Ansicht angezeigt und nicht geändert werden.