聚水潭
118.20M · 2026-03-13
上节详细 说明ref、reactive如何定义使用响应式数据。总结如下:
<template>
<h2>鱼类:{{ fish.name }}</h2>
<h2>价格:{{fish.price }}</h2>
<button @click="changeName">改变鱼</button>
<button @click="addPrice">涨价</button>
<h3>鱼的列表</h3>
<ul>
<li v-for="item in fishs" :key="item.id">
{{ item.name }}:{{ item.price }}
</li>
</ul>
<button @click="changeFirstPrice">改变第三条鱼的价格</button>
</template>
<script setup>
import { ref } from 'vue'
let fish = ref({ name: '鲫鱼', price: 10 });
let fishs = ref([
{id:'txdi01',name:'鲫鱼',price:10},
{id:'txdi02',name:'鲤鱼',price:20},
{id:'txdi03',name:'草鱼',price:30},
])
function changeName() {
fish.value.name = '草鱼';
console.log(fish);
console.log(fish.value);
}
function addPrice() {
fish.value.price += 10;
}
function changeFirstPrice() {
fishs.value[0].price += 10;
}
</script>
用ref定义的响应式对象,需要用.value去访问赋值。访问页面,发现他与reactive定义的响应式对象是一样的,除了reactive不需要用.value访问。如图
在点击按钮改变鱼,打印输入fish和fish.value,发现fish使用RefImpl定义,但 fish.value使用Proxy定义的对象,这与使用reactive定义是一样的。使用ref定义的响应式对象,底层使用reactive实现的。
reactive重新分配一个新对象会流失响应式是官方的说明。猛一看有些懵。我们从事例代码中去理解这句话的含义。事例中,定义let fish = reactive({ name: '鲫鱼', price: 10 }),创建5个按钮
详细代码
<template>
<h2>鱼类:{{ fish.name }}</h2>
<h2>价格:{{fish.price }}</h2>
<button @click="changeName">改变鱼的种类</button>
<button @click="addPrice">改变鱼的价格</button>
<div>
<button @click="changeallfish1">方式一改变整个鱼</button>
<button @click="changeallfish2">方式二改变整个鱼</button>
<button @click="changeallfish3">方式三改变整个鱼</button>
</div>
</template>
<script setup>
import { reactive } from 'vue'
let fish = reactive({ name: '鲫鱼', price: 10 });
function changeName() {
fish.name = '草鱼';
}
function addPrice() {
fish.price += 10;
}
function changeallfish1() {
fish={ name: '鲤鱼', price: 30 }
}
function changeallfish2() {
fish = reactive({ name: '鲤鱼鱼', price: 40 });
}
function changeallfish3() {
console.log('sadsd')
Object.assign(fish, { name: '带鱼', price: 50 })
console.log(fish);
}
</script>
<template>
<h2>鱼类:{{ fish.name }}</h2>
<h2>价格:{{fish.price }}</h2>
<button @click="changeallfish1">方式一改变整个鱼</button>
<button @click="changeallfish2">方式二改变整个鱼</button>
</template>
<script setup>
import { ref } from 'vue'
let fish = ref({ name: '鲫鱼', price: 10 });
function changeallfish1() {
fish.value={ name: '鲤鱼', price: 30 }
}
function changeallfish2() {
fish = ref({ name: '鲤鱼鱼', price: 40 });
}
</script>