1.直接赋值导致失去响应式
- 因为reactive数据被重新赋值后,原来数据的代理函数和最新数据的代理函数不是同一个
<template>
<div>
<div v-for="(item, index) in data" :key="index">{{ item }}</div>
<button @click="onUp">长大</button>
</div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
let data = reactive(['小猫', '小狗'])
const onUp = () => {
data = reactive(['大猫', '大狗'])
}
</script>
-
结果:
2.解决方法
- 方法一: reactive定义一个对象,对象里的每个属性都具有响应式
<template>
<div style="display: flex; margin-top: 30px;">
<div v-for="(item, index) in data.animals" :key="index" style="margin-left: 10px;">{{ item }}</div>
<button @click="onUp" style="margin-left: 10px;">长大</button>
</div>
<!-- user -->
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
let data = reactive({
animals: ['小猫', '小狗']
})
const onUp = () => {
data.animals = ['大猫', '大狗']
}
</script>
- 方法二:使用ref定义
<template>
<div style="display: flex; margin-top: 30px;">
<div v-for="(item, index) in data" :key="index" style="margin-left: 10px;">{{ item }}</div>
<button @click="onUp" style="margin-left: 10px;">长大</button>
</div>
<!-- user -->
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
let data = ref(['小猫', '小狗'])
const onUp = () => {
data.value = ['大猫', '大狗']
}
</script>
-
结果: