响应式数据是vue的一大亮点,下面我们来聊聊如何声明响应式数据
目录
直接声明变量
- 直接声明变量并不能使之拥有响应性
- 示例:
<script setup>
let num = 0;
const clickFun = () => {
console.log("num:", ++num);
}
</script>
<template>
<div style="display:flex;flex-direction: column;">
<span>num : {{num}}</span>
<button @click="clickFun()">修改</button>
</div>
</template>
- 运行结果:
- 多次点击按钮后,控制台打印的num值虽然有增加,但在html页面显示的num值却不变
ref(基本数据类型)
- 使用ref(基本数据类型)即可把一个基本数据类型的值转化为响应式并返回
- 基本数据类型:
- String
- Number
- BigInt
- Boolean
- Symbol
- Undefined
- Null
- 示例:
<script setup>
import { ref } from 'vue';
let num = 0;
let refNum = ref(0);
console.log("refNum:", refNum);
console.log("refNum.value", refNum.value);
const clickFun = () => {
console.log("num:", ++num);
console.log("refNum.value:" , ++refNum.value);
}
</script>
<template>
<div style="display:flex;flex-direction: column;">
<span>num : {{num}}</span>
<span>refNum : {{refNum}}</span>
<button @click="clickFun()">修改</button>
</div>
</template>
- 运行结果:
- 注意ref()返回的是一个refImpl的对象,它的value属性才是我们要的数据,所以在js中操作时需要.value,但在<template>中会自动展开为内部值
- 可以看到,通过ref()获取的变量是响应式的,会随着变量值的改变而体现在html页面中
reactive(对象)
- reactive()需要我们传入一个对象
- 示例:
<script setup>
import { ref,reactive } from 'vue';
let num = 0;
let refNum = ref(0);
let rea = reactive({
num:0
});
console.log("refNum:", refNum);
console.log("refNum.value", refNum.value);
console.log("rea", rea);
const clickFun = () => {
console.log("num:", ++num);
console.log("refNum.value:" , ++refNum.value);
console.log("rea.num:", ++rea.num);
}
</script>
<template>
<div style="display:flex;flex-direction: column;">
<span>num : {{num}}</span>
<span>refNum : {{refNum}}</span>
<span>rea.num : {{rea.num}}</span>
<button @click="clickFun()">修改</button>
</div>
</template>
- 运行结果:
- reactive()也可以让变量得到响应性
- 但它需要传入对象,而ref()需要传入基本数据类型
- 而且它返回的是一个proxy对象,但我们在js操作和在<template>绑定时,都可以直接访问和操作其内部变量。
Pure Bluffing In Poker – Why It Is Really A Profitable Act 다바오
포커 설치 방법 (jonbian.co)
квартира в новостройке от застройщика https://kvartiranovostroi.ru
купить 2 комнатную квартиру недвижимость новостройки купить
купить квартиру от застройщика https://zastroyshikekb54.ru
The Characteristics Of High-Quality Links 구글 상위노출 백링크
квартиры с отделкой от застройщика https://novyekvartiry2.ru
How Undertake A Business Card That Gets You Clients 비상금 대출 –
http://agpartimports.com/__media__/js/netsoltrademark.php?d=www.metooo.com/u/666fa9b90c59a92242676aa3,
How To Get To Five Good Of The Marketing Food Chain 윌슨 농구공 에볼루션
buy doxycycline us: doxycycline 100 mg forsale outside the us – cheap doxy
купить квартиру новостройка застройщика отделкой https://newkvartiry-spb.ru
Saved as a favorite, I really like your blog.
квартиры от застройщика цены жк https://novye-kvartiry-spb.ru
новые квартиры от застройщиков купить 3 комнатную квартиру
купить квартиру купить двухкомнатную квартиру
Beginners At Roulette 에볼루션 주식게임
Hello, Neat post. There is an issue together with your web site in internet explorer, could check this?
IE still is the marketplace leader and a large element of other people will leave
out your great writing due to this problem.
When You Should And Will Not Get Credit 보증금 대출
retin a renova
best price for doxycycline 100 mg without prescription: doxycycline 50mg tablets price – doxycycline online pharmacy canada
buying clomid for sale: can i order generic clomid pill – cost of clomid without dr prescription
Way cool! Some extremely valid points! I appreciate you penning this article and also the rest of the website is also really good.
https://faithful-watermelon-dc4vlp.mystrikingly.com/blog/506d6365ab3
doxycycline with out a rx: doxycycline 500 mg capsules – how much is doxycycline cost
Great Solutions To Generate A Boost In Traffic To Expenses – Part 1 검색엔진최적화 배우기
비아그라(성분명: 실데나필)를 처음 복용하려는 사용자들을 위한 가이드를 제공합니다. 이 가이드는 비아그라를 안전하고 효과적으로 사용하는 데 도움이 됩니다.
비아그라 복용 가이드
After looking into a number of the blog posts on your web page, I seriously appreciate your way of writing a blog. I book marked it to my bookmark site list and will be checking back in the near future. Please visit my website as well and let me know what you think.
where can i buy generic flomax
Option One Mortgage Loans – Getting An Option Arm Or Option One Mortgage Loan 전세 대출
(solventworks.com)
best canadian pharmacy no prescription
Привет!
Полезные советы по безопасной покупке диплома о высшем образовании
mockwacom.getbb.ru/viewtopic.php?f=11&t=1728&p=2364#p2364
Поможем вам всегда!.
site officiel
https://independent-canary-dc4vlp.mystrikingly.com/blog/8c6115484a0
There’s definately a great deal to learn about this topic. I like all of the points you made.
Seo: Five Important Points You Must Know About Backlinks seo 마케팅 – http://mchughontheweb.com/ –
Здравствуйте!
Приобрести диплом о высшем образовании.
tosiya.ru/cb-profile/pluginclass/cbblogs.html?action=blogs&func=show&id=298
cipro online no prescription in the usa: cipro online no prescription in the usa – ciprofloxacin
How To Further Improve Your Seo Reporting Skills 워드프레스 seo
diflucan cream otc
Привет!
Купить документ о получении высшего образования можно у нас в столице.
ast-diplom24.ru/otzyvy
Успехов в учебе!
купить однокомнатную квартиру в новостройке недорогие квартиры от застройщика
Indibet is a premier online casino offering a wide array of games including slots, table games, and live dealer options. Renowned for its user-friendly interface and robust security measures, Indibet ensures a top-notch gaming experience with exciting bonuses and 24/7 customer support.
купить квартиру в новостройке купить квартиру новостройке застройщика цены
Здравствуйте!
Заказать документ университета вы можете в нашем сервисе.
diploms-x.com/kupit-diplom-bakalavra-ili-specialista
best canadian online pharmacies
The future football star Shabab Al-Ahly https://dubai.shabab-al-ahli-ar.com was born in Dubai in 2000. From a young age, he showed exceptional football abilities and joined the youth academy of one of the UAE’s leading clubs, Shabab Al-Ahly.
The fascinating story of Ja Morant’s https://spain.atletico-madrid-ar.com meteoric rise, from status from rookie to leader of the Memphis Grizzlies and rising NBA superstar.
In the world of football, Atletico Madrid https://spain.atletico-madrid-ar.com has long been considered the second most important club in Spain after the dominant, Real Madrid.
Galatasaray https://turkey.galatasaray-ar.com is one of the most famous football clubs in Turkiye, with a glorious and eventful history.
generic doxycycline 200 mg: doxycycline online pharmacy uk – doxycycline 150 mg cost
Things Everyone Ought To Know About Getting An Advance Payday Loan 리드코프 무직자 대출