Vue3 響應(yīng)式數(shù)據(jù) reactive使用方法
ref 與 reactive 是 vue3 提供給我們用于創(chuàng)建響應(yīng)式數(shù)據(jù)的兩個方法。
reactive 常用于創(chuàng)建引用數(shù)據(jù),例如:object、array 等。
reactive 則是通過 proxy 來實現(xiàn)的響應(yīng)式數(shù)據(jù),并配合 reflect 操作的源對象。
reactive 創(chuàng)建引用數(shù)據(jù):
<template>
<p>姓名:{{ info.name }}</p>
<p>年齡:{{ info.age }}</p>
<p>性別:{{ info.sex }}</p>
<button @click="editInfo">修改信息</button>
</template>
<script>
// 引入 reactive 函數(shù)
import { reactive } from 'vue'
export default {
name: "Home",
setup() {
// 使用 reactive 創(chuàng)建引用數(shù)據(jù)
const info = reactive({
name: "張三",
age: 20,
sex: "男"
});
// 創(chuàng)建方法
const editInfo = () => {
info.name = "李四";
info.age = 22;
info.sex = "女";
// reactive 創(chuàng)建的數(shù)據(jù)是一個 proxy 對象,不需要通過 value 獲取
console.log(info);
}
// 返回數(shù)據(jù)
return {
info,
editInfo
}
}
}
</script>reactive 只能創(chuàng)建引用數(shù)據(jù)(數(shù)組或?qū)ο螅?。另外通過 reactive 創(chuàng)建的數(shù)據(jù)可以直接使用,不需要通過 value 屬性獲取。

注:reactive 創(chuàng)建的是一個深層次的數(shù)據(jù)對象,不論多少層,reactive 都能檢測到數(shù)據(jù)的變化
reactive 創(chuàng)建數(shù)組 :
<template>
<p v-for="item in userList" :key="item">{{ item }}</p>
<button @click="editUser">修改人員</button>
</template>
<script>
// 引入 reactive 函數(shù)
import { reactive } from 'vue'
export default {
name: "Home",
setup() {
// 使用 reactive 創(chuàng)建數(shù)組
const userList = reactive(["張三", "李四", "王五"]);
// 創(chuàng)建方法
const editUser = () => {
// vue3 通過下標(biāo)修改數(shù)據(jù)時,頁面也會實時更新
userList[0] = "張三豐";
console.log(userList);
}
// 返回數(shù)據(jù)
return {
userList,
editUser
}
}
}
</script>注:vue3 通過下標(biāo)修改數(shù)據(jù)時,頁面也會實時更新。

到此這篇關(guān)于Vue3 響應(yīng)式數(shù)據(jù) reactive使用方法的文章就介紹到這了,更多相關(guān)Vue3 響應(yīng)式數(shù)據(jù) reactive內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Vue3.0使用ref和reactive來創(chuàng)建響應(yīng)式數(shù)據(jù)
- Vue3中使用ref與reactive創(chuàng)建響應(yīng)式數(shù)據(jù)的示例代碼
- vue3 reactive定義的引用類型直接賦值導(dǎo)致數(shù)據(jù)失去響應(yīng)式問題
- Vue3關(guān)于響應(yīng)式數(shù)據(jù)類型詳解(ref、reactive、toRef、及toRefs)
- vue3中如何使用ref和reactive定義和修改響應(yīng)式數(shù)據(jù)(最新推薦)
- Vue 中 reactive創(chuàng)建對象類型響應(yīng)式數(shù)據(jù)的方法
相關(guān)文章
vuejs2.0運用原生js實現(xiàn)簡單的拖拽元素功能示例
本篇文章主要介紹了vuejs2.0運用原生js實現(xiàn)簡單的拖拽元素功能示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
使用konva和vue-konva庫實現(xiàn)拖拽滑塊驗證功能
這篇文章主要介紹了使用konva和vue-konva完成前端拖拽滑塊驗證功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Vue中mixins的使用方法以及實際項目應(yīng)用指南
vue中提供了一種混合機制--mixins,用來更高效的實現(xiàn)組件內(nèi)容的復(fù)用,下面這篇文章主要給大家介紹了關(guān)于Vue中mixins的使用方法以及實際項目應(yīng)用指南,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-03-03
html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁
這篇文章主要為大家介紹了html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08

