Vue3响应式数据ref

简介: Vue3响应式数据ref

ref 函数:用于创建 基础数据类型,例如:string、number、boolean 等。

ref 函数:也能创建 引用数据类型,不过更推荐使用:《Vue3 响应式数据 reactive》 创建。

// 引入 ref 函数
import { ref } from "vue";
// 创建数据
let 变量名 = ref(数据);

创建基础数据类型

<template>
  <h3>响应式数据 ref</h3>
  <p>商品数量:{{ num }}</p>
  <button @click="addNum">增加</button>
</template>
 
<script setup>
// 引入 ref 函数
import { ref } from "vue";
// 使用 ref 创建基本数据
let num = ref(10);
 
const addNum = () => {
  num.value++;
  console.log(num);
}
</script>

效果:

注:在 script 标签中,需要通过 value 属性才能使用或修改 ref 数据。而在 template 标签中可以直接使用。

创建引用数据类型【不推荐】

<template>
  <h3>响应式数据 ref</h3>
  <p>姓名:{{ info.name }}</p>
  <p>年龄:{{ info.age }}</p>
  <button @click="editInfo">编辑</button>
</template>
 
<script setup>
// 引入 ref 函数
import { ref } from "vue";
// 使用 ref 创建引用数据
let info = ref({
  name: "张三",
  age: 20
});
 
const editInfo = () => {
  info.value.name = "李四";
  info.value.age = 99;
  console.log(info.value);
}
</script>


相关文章
|
1天前
|
JavaScript 定位技术 API
在 vue3 中使用高德地图
在 vue3 中使用高德地图
8 0
|
1天前
vue3 键盘事件 回车发送消息,ctrl+回车 内容换行
const textarea = textInput.value.textarea; //获取输入框元素
9 3
|
4天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
14 0
|
4天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
4天前
|
JavaScript 前端开发 安全
Vue3官方文档速通(下)
Vue3官方文档速通(下)
15 0
|
4天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
20 0
|
4天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
26 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
10 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
8 0