vue3如何定義變量
更新時間:2026年05月16日 14:13:27 作者:冰涼小腳
文章主要講述了Vue中ref和reactive兩種定義變量的方法,ref適用于簡單類型數(shù)據(jù),需在setup中定義并return,通過.value獲取和操作;reactive適用于復(fù)雜數(shù)據(jù),注意在使用時正確調(diào)用變量
1、定義變量
1.1、ref
一般用來處理簡單類型的數(shù)據(jù)
注意點:
- 定義變量在setup函數(shù)中用vue的ref方法
- 定義的變量以及方法需要setup函數(shù)進(jìn)行return出來,才可以在html代碼中使用
- 方法中調(diào)用變量需要打點到變量的value進(jìn)行獲取和操作
<template>
<div>
<div class="count">
count: {{ count }}
</div>
<button @click="countaddFn">count++</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup () {
let count=ref(0)
let countaddFn=()=>{
count.value++
}
return {
count,countaddFn
}
}
}
</script>
1.2、reactive
一般用于定義復(fù)雜數(shù)據(jù)
<template>
<div>
<table border="1">
<tr>
<th>id</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
</tr>
<tr v-for="item in user" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.gender }}</td>
</tr>
</table>
<button @click="modifyTheFn">修改數(shù)據(jù)</button>
</div>
</template>
<script>
import { reactive } from 'vue';
export default {
setup () {
// 復(fù)雜類型數(shù)據(jù)定義
let user=reactive([
{id:1,name:'張三',age:20,gender:'男'},
{id:2,name:'李四',age:30,gender:'中性'},
{id:3,name:'王五',age:40,gender:'女'},
{id:4,name:'老六',age:50,gender:'未知'},
])
function modifyTheFn(){
user[1].name='老七'
}
return {
user,modifyTheFn
}
}
}
</script>
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue.js利用defineProperty實現(xiàn)數(shù)據(jù)的雙向綁定
本篇文章主要介紹了用Node.js當(dāng)作后臺、jQuery寫前臺AJAX代碼實現(xiàn)用戶登錄和注冊的功能的相關(guān)知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04
element?el-tree折疊收縮的實現(xiàn)示例
本文主要介紹了element?el-tree折疊收縮的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

