- 当你看到如下信息时,说明你的项目启动成功了!!!
===========================================================================
对比 Vue2 中 OPTIONS API,data 和 methods 的定义如下所示
在 Vue3 中,上述的方式依然可以使用。但是我们今天要使用 Vue3 的 Composition API 完成同样的功能
3.1 Composition API setup() 函数 的响应式引用
学习指引:
- 在 setup 函数中定义参数
- 在 setup 函数中定义方法
- 在 setup 函数中定义计算属性
setup 函数
-
使用 Composition API 的入口
-
在 beforeCreate 之前调用
-
在 setup 中没有 this 关键字
ref 函数
-
返回一个 响应式引用
-
name 是一个响应式对象
姓名:{{name}}
年龄:
<button type=“button” @click=“changeAge(-1)”>+
{{age}}
<button type=“button” @click=“changeAge(1)”>+
出生年份: (插值表达式实现) {{2020 - age}}
出生年份:(计算属性实现)
<button type=“button” @click=“changeYear(-1)”>-
{{year}}
<button type=“button” @click=“changeYear(1)”>+
3.2 Composition API setup() 函数 响应式对象
上面的代码是不是看起来很冗余,这下我们使用 响应式对象 来简化上面的代码
-
使用 reactive 将一个对象 => 响应式对象
-
使用 toRefs 将 响应式对象 => 普通对象
姓名:{{name}}
年龄:
<button type=“button” @click=“changeAge(-1)”>+
{{age}}
<button type=“button” @click=“changeAge(1)”>+
出生年份: (插值表达式实现) {{2020 - age}}
出生年份:(计算属性实现)
<button type=“button” @click=“changeYear(-1)”>-
{{year}}
<button type=“button” @click=“changeYear(1)”>+