响应式数据是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>绑定时,都可以直接访问和操作其内部变量。
Привет, друзья!
Легальные способы покупки диплома о среднем полном образовании
http://www.horn-fahrzeugaufbereitung.de/купить-дипломы-олимпиад.html
https://naveridbuy.blogspot.com/2024/07/blog-post_41.html
Store Your Favorite Music On Your R4 Card 대학생 생활비 대출
заказать продвижение сайта казань https://seo-raskrutka43.ru
seo агентства раскрутка сайтов казань
Помощь студентам в выполнении рефератов https://referatkupit-oline.ru. Низкие цены и быстрое написание рефератов!
lasix 20 mg tablet
Unsecured Loans Are There For All The Needs 공무원 대출
doxycycline generic price
Привет, друзья!
Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
vistasalamat.com/диплом-магистра-2014-20242024-фото/
You have made some really good points there. I looked on the internet for additional information about the issue and found most individuals will go along with your views on this web site.
https://xn--lm-o02ik82aiqcqsko8mfg5a1sb.mystrikingly.com/blog/8d0854f8b59
cialis singapore pharmacy
https://translucent-shrimp-dc4vlt.mystrikingly.com/blog/7496b4392ce
Love Your Cash – Love Your Wallet – Love Your Finances 다바오
포커 하는법 (yoavguttmann.com)
https://xn--gz-2e2i723b91ktjas9l307b.mystrikingly.com/blog/2e590172c9b
Добрый день!
Купить документ о получении высшего образования можно у нас в Москве.
ast-diplom.com/kupit-diplom-tehnikuma-kolledzha
Красивая музыка https://melodia.space для души слушать онлайн.
79 슬롯
군주와 신하들이 믿지 않으니 믿게 하라.
Accessibility Team Meeting Notes https://make.wordpress.org/accessibility/2021/06/11/accessibility-team-meeting-notes-june-11-2021
Increase Your Profits With Search Engine Ranking 검색엔진최적화
How To Host A Texas Holdem Party 라이브 카지노 (http://digitalbidsale.com)
https://viastoer.blogspot.com/2024/07/blog-post_92.html
How Aren’t Jumbo Loan Installments Low 대출
Заказать курсовую работу https://kursovye-napishem.ru в Москве: цены на написание и выполнение, недорого
슬롯 무료 게임
Liu Jie가 말했듯이 그는 타고 쏘고 검술을 할 수 있으며 천문학과 지리학을 공부했습니다.
Заказать дипломную работу https://diplomzakazat-oline.ru недорого. Дипломные работы на заказ с гарантией.
Aw, this was an extremely good post. Finding the time and actual effort to create a very good article… but what can I say… I put things off a whole lot and never seem to get nearly anything done.
There is definately a lot to find out about this subject. I love all of the points you have made.
Здравствуйте!
Приобрести диплом о высшем образовании.
c90226sl.beget.tech/2024/07/04/kak-najti-nadezhnyj-onlajn-magazin-s-ogromnym-katalogom-diplomov/
Online Poker – Is Holdem Still Profitable Thinking About 2011?
에볼루션 유출
10 Inquiries To Ask Your Seo Provider 백링크 프로그램
Заказать контрольную работу https://kontrolnye-reshim.ru, недорого, цены. Решение контрольных работ на заказ срочно.
купить квартиру в новостройке недорого https://kvartira-novostroyka2.ru
Помощь в решении задач https://zadachireshaem-online.ru. Опытные авторы с профессиональной подготовкой окажут консультацию в решении задач на заказ недорого, быстро, качественно
Gift Card – Gift Card Ideas How The Recipients Adore 청년 전세 대출
https://xn--gd-2e2i723b91ktjas9l307b.mystrikingly.com/blog/d2e6a3e45cd
This site was… how do I say it? Relevant!! Finally I have found something that helped me. Appreciate it.
The Hidden Account About Solana’s Originator Toly’s Triumph
Post Two Mugs of Coffee plus a Ale
Yakovenko, the visionary the brainchild behind Solana, initiated his quest with a routine ritual – a couple of coffees and an ale. Unaware to him, those moments would ignite the wheels of his journey. Currently, Solana remains as an influential participant in the cryptocurrency realm, having a market value of billions.
Ethereum ETF Debut
The Ethereum exchange-traded fund lately made its debut with a huge trading volume. This significant event experienced numerous spot Ethereum ETFs from various issuers be listed on U.S. exchanges, bringing unseen activity into the generally calm ETF trading market.
SEC Sanctions Ethereum ETF
The Commission has formally approved the Ethereum Spot ETF to trade. Being a cryptographic asset that includes smart contracts, it is expected that Ethereum to majorly affect the digital currency industry due to this approval.
Trump’s Bitcoin Strategy
As the election draws near, Trump positions himself as the ‘Crypto President,’ frequently displaying his endorsement of the cryptocurrency industry to win voters. His strategy differs from Biden’s approach, aiming to capture the interest of the digital currency community.
Elon Musk’s Influence
Elon Musk, a well-known figure in the cryptocurrency space and a backer of the Trump camp, shook things up once more, boosting a meme coin related to his antics. His engagement keeps shaping the market environment.
Recent Binance News
Binance’s subsidiary, BAM, has been permitted to invest customer funds into U.S. Treasuries. In addition, Binance marked its 7th anniversary, underscoring its development and acquiring multiple compliance licenses. In the meantime, the company also revealed plans to discontinue several major crypto trading pairs, altering the market landscape.
AI and Market Trends
The chief stock analyst at Goldman Sachs recently stated that artificial intelligence won’t trigger a major economic changeHere’s the spintax version of the provided text with possible synonyms
zie bericht
Getting An Offshore Family Savings Via The Online World 다바오 포커 아이폰
Online Personal Loan – Apply And Get Approved Fast
In Only One Or Two Hours! 햇살론 대출
купить новостройку недорого купить 1 комнатную новостройку
how to get flomax
купить новостройку цены застройщика купить 1 квартиру застройщика
슬롯 게임 꽁 머니
새로운 황제가 왕위에 오른 것은 좋은 일이었고, 그 역시 그의 조카였습니다.
Привет, друзья!
Купить диплом о высшем образовании.
myanimalgram.com/read-blog/267
The very next time I read a blog, Hopefully it won’t disappoint me as much as this one. I mean, Yes, it was my choice to read, however I genuinely believed you would probably have something interesting to say. All I hear is a bunch of complaining about something you can fix if you were not too busy seeking attention.
Online Bank Cd Rates Tx (Texas) 다바오 머니 분양
Привет!
Заказать документ о получении высшего образования можно у нас.
diplomyx24.ru/kupit-diplom-magistra
Хорошей учебы!