点此查看 所有教程、项目、源码导航
文章目录
1. 本篇说明
上一节我们在事件绑定里面提前体验了 ref,这一节专门讲两件核心内容:
<script setup>语法糖是什么、为什么推荐它(Vue3 主流写法)ref的完整用法,用来给数字、字符串、布尔这类基础类型做响应式
后续所有示例,我们统一使用
<script setup>写法。
2. 什么是 script setup
<script setup> 是 Vue3 的编译语法糖,是现在项目里的默认写法。
对比旧选项式 API,它更简洁,也是我们整个教程统一使用的写法。
核心特点
- 标签加上
setup:<script setup> - 里面写的变量、函数,可以直接在 template 模板中使用,不需要手动 return
- 代码更短,逻辑内聚,TS 类型支持更好
- 它本质是编译时语法糖,不是运行时 API
对比演示:
html
<!-- script setup 写法(我们用这个) -->
<template>
<p>{{ msg }}</p>
</template>
<script setup>
const msg = 'hello setup'
</script>
html
<!-- 旧写法(了解即可,不再推荐) -->
<template>
<p>{{ msg }}</p>
</template>
<script>
export default {
setup() {
const msg = 'hello setup'
return { msg }
}
}
</script>
讲解:
- 旧写法:定义完变量,必须
return出去,模板才能访问 - setup 语法糖:不用 return,顶层变量、函数直接暴露给模板
3. 普通变量的问题(重点)
先看普通 const / let 变量:
html
<template>
<div>
<p>计数:{{ num }}</p>
<button @click="add">点我+1</button>
</div>
</template>
<script setup>
// 普通变量,非响应式
let num = 0
const add = () => {
num++
console.log(num) // 控制台打印数字确实变了
}
</script>
现象:点击按钮,控制台数字在增加,但是页面上的文字不会刷新。
原因:普通 JS 变量,Vue 不会监听它的变化,无法自动更新视图。
想要实现【数据变,页面自动更新】,就要使用响应式 API。
4. ref 基础用法(基础类型响应式)
ref 用来创建响应式数据,适合:数字、字符串、布尔值、null、undefined 这类基础类型。使用三步:
- 从 vue 导入
ref ref(初始值)创建响应式变量- script 内部读写,需要
.value;模板中自动解包,不用.value
html
<template>
<div>
<p>计数:{{ num }}</p>
<button @click="add">+1</button>
<button @click="num++">行内直接+1</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
// 创建响应式变量,初始值0
const num = ref(0)
const add = () => {
// ✅ script 里面修改,必须写 .value
num.value++
}
</script>
多几个基础类型示例
html
<template>
<div>
<p>名字:{{ name }}</p>
<p>是否选中:{{ isOk }}</p>
<button @click="change">修改内容</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const name = ref('张三')
const isOk = ref(false)
const change = () => {
name.value = '李四'
isOk.value = true
}
</script>
5. 高频易错点(必记)
- ✅ script setup 内部:读写 ref 数据,必须加 .value
js
const count = ref(10)
count.value = 20
- ✅ template 模板里面:直接写变量名,不要写 .value
html
<p>{{ count }}</p>
- ❌ 不要混淆:ref 是包装对象,
console.log(count)打印出来是一个 RefImpl 对象,不是直接数字
js
console.log(count) // RefImpl { value: 10 }
console.log(count.value) // 10
6. 综合小案例:文字切换
html
<template>
<div>
<p>{{ tip }}</p>
<button @click="toggleTip">切换文字</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const tip = ref('原始文字')
const toggleTip = () => {
tip.value = '修改后的文字'
}
</script>
7. 小结
<script setup>是 Vue3 推荐语法糖,顶层变量、函数直接在模板使用,不用 return- 普通 let/const 变量不是响应式,修改不会更新页面
ref用于基础类型响应式:数字、字符串、布尔- 口诀:脚本里加.value,模板里直接写