认识Vue3
1. Vue3组合式API体验
通过 Counter 案例 体验Vue3新引入的组合式API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <button @click="addCount"> {{count}} </button> </template> <script> //vue2语法 export default { data(){//响应数据 return { count:0 } }, methods:{ addCount(){//自增事件 this.count++ } } } </script>
|
1 2 3 4 5
| <script setup>//vue3版本 import { ref } from 'vue' const count = ref(0) const addCount = ()=> count.value++ </script>
|
特点:
- 代码量变少
- 分散式维护变成集中式维护
2. Vue3更多的优势

使用create-vue搭建Vue3项目
1. 认识create-vue
create-vue是Vue官方新的脚手架工具,(之前是webpack)底层切换到了 vite (下一代前端工具链),为开发提供极速响应

2. 使用create-vue创建项目
前置条件 - 已安装16.0或更高版本的Node.js
执行如下命令,这一指令将会安装并执行 create-vue
1 2
| npm -v npm init vue@latest
|

到目录后输入 code ./ 用vscode打开
启动后的页面也是一个不错的学习资源
熟悉项目和关键文件

组合式API - setup选项
1. setup选项的写法和执行时机
写法
1 2 3 4 5 6 7 8 9 10
| <script> export default { setup(){ }, beforeCreate(){ } } </script>
|
执行时机
在beforeCreate钩子之前执行

2. setup中写代码的特点
在setup函数中写的数据和方法需要在末尾以对象的方式return,才能给模版使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script> export default { setup(){ const message = 'this is message' const logMessage = ()=>{ console.log(message) } // 必须return才可以 return { message, logMessage } } } </script>
|
3. <script setup>语法糖
script标签添加 setup标记,不需要再写导出语句,默认会添加导出语句
1 2 3 4 5 6
| <script setup> const message = 'this is message' const logMessage = ()=>{ console.log(message) } </script>
|
1.setup选项的执行时间?
beforeCreate钩子之前自动执行
1.setup写代码的特点是什么?
定义数据 + 函数 然后以对象方式return
3.<script setup>解决了是吗问题?
经过语法糖的封装更简单的使用组合式API
4.setup中的this还指向组件实例吗?
指向undefined
组合式API - reactive和ref函数
1. reactive
接受对象类型数据的参数传入并返回一个响应式的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script setup> // 导入 import { reactive } from 'vue' // 执行函数 传入一个对象类型的参数 变量接收 const state = reactive({ msg:'this is msg' }) const setSate = ()=>{ // 修改数据更新视图 state.msg = 'this is new msg' } </script>
<template> {{ state.msg }} <button @click="setState">change msg</button> </template>
|
2. ref
接收简单类型或者对象类型的数据传入并返回一个响应式的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <script setup> // 导入 import { ref } from 'vue' // 执行函数 传入参数 变量接收 const count = ref(0) const setCount = ()=>{ // 修改数据更新视图必须加上.value count.value++ } </script>
<template> <button @click="setCount">{{count}}</button> </template>
|
3. reactive 对比 ref
- 都是用来生成响应式数据
- 不同点
- reactive不能处理简单类型的数据
- ref参数类型支持更好,但是必须通过.value做访问修改
- ref函数内部的实现依赖于reactive函数
- 在实际工作中的推荐
- 推荐使用ref函数,减少记忆负担,小兔鲜项目都使用ref
组合式API - computed
计算属性基本思想和Vue2保持一致,组合式API下的计算属性只是修改了API写法
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script setup> // 导入 import {ref, computed } from 'vue' // 原始数据 const count = ref(0) // 计算属性 const doubleCount = computed(()=>count.value * 2)
// 原始数据 const list = ref([1,2,3,4,5,6,7,8]) // 计算属性list 筛选大于2的所有项 - filter const filterList = computed(item=>item > 2) </script>
|
最佳实践
1.计算属性中不应该有“副作用”
比如 : 异步请求/修改dom 我可以交给watch函数使用
2.避免直接修改计算属性的值
计算属性应该是只读的
组合式API - watch
侦听一个或者多个数据的变化,数据变化时执行回调函数,俩个额外参数 immediate控制立刻执行,deep开启深度侦听
1. 侦听单个数据
1 2 3 4 5 6 7 8 9
| <script setup> // 1. 导入watch import { ref, watch } from 'vue' const count = ref(0) // 2. 调用watch 侦听变化 watch(count, (newValue, oldValue)=>{ console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`) }) </script>
|
2. 侦听多个数据
侦听多个数据,第一个参数可以改写成数组的写法
1 2 3 4 5 6 7 8 9 10
| <script setup> // 1. 导入watch import { ref, watch } from 'vue' const count = ref(0) const name = ref('cp') // 2. 调用watch 侦听变化 watch([count, name], ([newCount, newName],[oldCount,oldName])=>{ console.log(`count或者name变化了,[newCount, newName],[oldCount,oldName]) }) </script>
|
在侦听器创建时立即出发回调,响应式数据变化之后继续执行回调
1 2 3 4 5 6 7 8 9 10 11
| <script setup> // 1. 导入watch import { ref, watch } from 'vue' const count = ref(0) // 2. 调用watch 侦听变化 watch(count, (newValue, oldValue)=>{ console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`) },{ immediate: true }) </script>
|
4. deep
通过watch监听的ref对象默认是浅层侦听的,直接修改嵌套的对象属性不会触发回调执行,需要开启deep
deep性能损耗 尽量不开启 可以使用精确监听
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <script setup> // 1. 导入watch import { ref, watch } from 'vue' const state = ref({ count: 0 }) // 2. 监听对象state watch(state, ()=>{ console.log('数据变化了') }) const changeStateByCount = ()=>{ // 直接修改不会引发回调执行 state.value.count++ } </script>
<script setup> // 1. 导入watch import { ref, watch } from 'vue' const state = ref({ count: 0 }) // 2. 监听对象state 并开启deep watch(state, ()=>{ console.log('数据变化了') },{deep:true}) const changeStateByCount = ()=>{ // 此时修改可以触发回调 state.value.count++ } </script>
|
精确监听某个具体属性
1 2 3 4 5 6
| watch( ()=>state.value.age, ()=>{ console.log('age变化了') } )
|
组合式API - 生命周期函数
1. 选项式对比组合式

2. 生命周期函数基本使用
- 导入生命周期函数
- 执行生命周期函数,传入回调
在Vue中“挂载” 用大白话解释就算: 把你的Vue实例生成的HTML内容“安装”到页面的某个真实DOM元素中,让塔显示出来。
1 2 3 4 5 6
| <scirpt setup> import { onMounted } from 'vue' onMounted(()=>{ // 自定义逻辑 }) </script>
|
3. 执行多次
生命周期函数执行多次的时候,会按照顺序依次执行
1 2 3 4 5 6 7 8 9 10
| <scirpt setup> import { onMounted } from 'vue' onMounted(()=>{ // 自定义逻辑 })
onMounted(()=>{ // 自定义逻辑 }) </script>
|
组合式API - 父子通信
1. 父传子
基本思想
- 父组件中给子组件绑定属性
- 子组件内部通过props选项接收数据

2. 子传父
基本思想
- 父组件中给子组件标签通过@绑定事件
- 子组件内部通过 emit 方法触发事件

组合式API - 模版引用
概念:通过 ref标识 获取真实的 dom对象或者组件实例对象
1. 基本使用
实现步骤:
- 调用ref函数生成一个ref对象
- 通过ref标识绑定ref对象到标签

2. defineExpose
默认情况下在 <script setup>语法糖下组件内部的属性和方法是不开放给父组件访问的,可以通过defineExpose编译宏指定哪些属性和方法容许访问
说明:指定testMessage属性可以被访问到

获取模板引用的时机是什么? 组件挂载完毕
组合式API - provide和inject
1. 作用和场景
顶层组件向任意的底层组件传递数据和方法,实现跨层组件通信

2. 跨层传递普通数据
实现步骤
- 顶层组件通过
provide 函数提供数据
- 底层组件通过
inject 函数提供数据

3. 跨层传递响应式数据
在调用provide函数时,第二个参数设置为ref对象

4. 跨层传递方法
顶层组件可以向底层组件传递方法,底层组件调用方法修改顶层组件的数据 谁的数据谁负责修改

综合案例

1. 项目地址
1
| git clone http://git.itcast.cn/heimaqianduan/vue3-basic-project.git
|
2. 项目说明
- 模版已经配置好了案例必须的安装包
- 案例用到的接口在 README.MD文件 中
- 案例项目有俩个分支,main主分支为开发分支,complete分支为完成版分支供开发完参考
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| <script setup> import Edit from './components/Edit.vue' import { onMounted, ref } from 'vue' import axios from 'axios'
const list = ref([]) const getList = async () => { const res = await axios.get('/list') list.value = res.data; }
onMounted(() => getList())
const onDelete = async (id) => { console.log(id); await axios.delete(`/del/${id}`) getList() }
const editRef = ref(null) const onEdit = (row) => { editRef.value.open(row) }
</script>
<template> <div class="app"> <el-table :data="list"> <el-table-column label="ID" prop="id"></el-table-column> <el-table-column label="姓名" prop="name" width="150"></el-table-column> <el-table-column label="籍贯" prop="place"></el-table-column> <el-table-column label="操作" width="150"> <template #default="{ row }"> <el-button type="primary" @click="onEdit(row)" link>编辑</el-button> <el-button type="danger" @click="onDelete(row.id)" link>删除</el-button> </template> </el-table-column> </el-table> </div> <Edit ref="editRef" @on-update="getList" /> </template>
<style scoped> .app { width: 980px; margin: 100px auto 0; } </style>
|
Edit.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| <script setup>
import { ref } from 'vue' import axios from 'axios'
const dialogVisible = ref(false)
const form = ref({ name: '', place: '', id: '' }) const open = (row) => { console.log(row) form.value.name = row.name form.value.place = row.place form.value.id = row.id dialogVisible.value = true } defineExpose({ open })
const emit = defineEmits(['on-update']) const onUpdate = async () => { await axios.patch(`/edit/${form.value.id}`, { name: form.value.name, place: form.value.place }) dialogVisible.value = false emit('on-update') }
</script>
<template> <el-dialog v-model="dialogVisible" title="编辑" width="400px"> <el-form label-width="50px"> <el-form-item label="姓名"> <el-input placeholder="请输入姓名" v-model="form.name" /> </el-form-item> <el-form-item label="籍贯"> <el-input placeholder="请输入籍贯" v-model="form.place" /> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="onUpdate">确认</el-button> </span> </template> </el-dialog> </template>
<style scoped> .el-input { width: 290px; } </style>
|
mock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import Mock from "mockjs"
const arr = [] for (let i = 0; i < 10; i++) { arr.push({ id: Mock.mock("@id"), name: Mock.mock("@cname"), place: Mock.mock("@county(true)"), }) } export default [ { url: "/list", method: "get", response: () => { return arr }, }, { url: "/del/:id", method: "delete", response: (req) => { const index = arr.findIndex((item) => item.id === req.query.id) if (index > -1) { arr.splice(index, 1) return { success: true } } else { return { success: false } } }, }, { url: "/edit/:id", method: "patch", response: ({ query, body }) => { const item = arr.find((item) => item.id === query.id) if (item) { item.name = body.name item.place = body.place return { success: true } } else { return { success: false } } }, }, ]
|