Vue-Three

178 阅读6分钟

Vue-three

一 创建项目

  1. vue3项目命令:npm init vue@latest
  2. 需求类型选择,根据图片相似

image.png

3 根据文档命令创建项目 4 项目创建成功

二 熟悉项目目录和关键文件

image.png 关键文件 1 vite.config.js-项目配置文件 基于vite的配置 2 package.json-项目包文件 核心依赖变成了 Vue3.x 和 vite 3 main.js-入口文件 createApp函数创建应用实例 4 app.vue-根组件SFC单文件组件 script-template-style 5 index.html-单页入口 提供id为app的挂载点

三 组合式API-setup选项

1 setup选项的写法和执行时机

1 删除初始化的文件

<!-- 开关: 容许在script书写组合式API -->
<script >
   export default {
    setup(){
      console.log(this.setup)
    },
    beforeCreate(){
      console.log('beforeCreate')
    }
   }
</script>
<template>
  <!-- 不再要求唯一根元素 -->
  <div> this is div </div>
</template>

2 setup选项中写代码的特点

2 当点击时,触发事件

<!-- 开关: 容许在script书写组合式API -->
<script >
   export default {
    setup(){
      console.log('setup',this)
      const message = 'this is message'
      const logMessage = () => {
        console.log(message)
      }
      return {
        message,
        logMessage
      }
    },
    beforeCreate(){
      console.log('beforeCreate')
    }
   }
</script>
<template>
  <!-- 不再要求唯一根元素 -->
  <div>
  {{ message }}
  <button @click="logMessage">LOG</button>
   </div>
</template>



3script setup 语法糖

原始复杂写法

<script >
   export default {
    setup(){
      console.log('setup',this)
      const message = 'this is message'
      const logMessage = () => {
        console.log(message)
      }
      return {
        message,
        logMessage
      }
    },
    beforeCreate(){
      console.log('beforeCreate')
    }
   }
</script>

语法糖写法

<script setup >
 const message = 'this is message'
 const logMessage = () => {
   console.log(message)
 }
</script>

小结:

1.setup选项的执行时机

  • beforeCreate钩子之前 自动执行
  1. setup写代码的特点是什么?
  • 定义数据+函数 然后以对象方式return
  1. script setup 解决了什么问题?
  • 经过语法糖的封装更简单的使用组合式API
  1. setup中的this还指向组件实例吗?
  • 指向undefind

四 组合式API-reactive和ref函数

四点一

  • reactive()
  • 作用:接收对象类型数据的参数传入并返回一个响应式的对象
  • 核心步骤:
  • 代码:
<script setup >
// 导入函数
import { reactive  } from 'vue'

// 执行函数 传入一个对象类型的参数 变量接收
const state = reactive({
  count:0
})

const setCount = () => {
  state.count++
}
</script>
<template>
  <!-- 不再要求唯一根元素 -->
  <div>
    <button @click="setCount">{{ state.count }}</button>
   </div>
</template>
  • 1 从 vue 包中导入 reactive函数
  • 2 在 script setup 中执行 reative 函数并传入类型为对象的初始值,并使用变量接收返回值

四点二

  • ref()
  • 作用: 接收简单类型或对象类型的数据传入并返回一个响应式的对象
  • 核心步骤:
  • 代码
<script setup >
// 导入 ref函数
   import { ref } from 'vue'
// 执行函数 传入参数[简单类型 + 对象类型] 变量接收
   const  count = ref(0)


   const setCount = () => {
    // 脚本区域修改ref产生的响应式对象数据 必须通过 .value属性
    count.value++
   }
</script>
<template>
  <!-- 不再要求唯一根元素 -->
  <div>
  <button @click="setCount">{{ count  }}</button>
   </div>
</template>
  • 1 从 vue包中导入ref函数

  • 2 在 script setup 中执行ref函数并传入初始值,使用变量接收 ref函数的返回值

  • 小结:

  1. reactive和ref函数的共同作用是什么?
  • 用函数调用的方式生成响应式数据
  1. reactive Vs ref
  • 1 reactive不能处理简单类型的数据
  • 2 ref参数类型支持更好但是必须通过.value访问修改
  • 3 ref函数的内部实现依赖reactive函数

3.在实际工作中推荐使用哪个?

  • 推荐使用ref函数,更加灵活,小兔鲜项目主用ref

五 组合式API-computed

  • computed计算属性函数
  • 计算属性基本思想和Vue2的完全一致,组合式API下的计算属性只是修改了写法 核心步骤:
  1. 导入computed函数
  2. 执行函数 在回调参数中 return基于响应式数据做计算的值,用变量接收
  • 代码:
  • 计算属性小案例

image.png

  • 计算公式: 始终从原始响应式数组中筛选出大于2的所有项 - filter
<script setup >
 // 原始响应式数据
 import { ref } from 'vue'
 const list = ref([1,2,3,4,5,6,7,8])
 // 导入computed
 import { computed } from 'vue'
 // 执行函数 return计算之后的值 变量接收
 const computedList = computed (() => {
  return list.value.filter(item => item>2)
 })

 setTimeout(() => {
  list.value.push(9.10)
 },3000)
</script>
<template>
  <!-- 不再要求唯一根元素 -->
  <div>
   原始响应式数组- {{ list }}
   </div>
  
  <div>
    计算属性数组 - {{ computedList }}
  </div>
</template>
  • 最佳实践
  • 1 计算机属性不应该有"副作用" 比如异步请求/修改dom
  • 2 避免直接修改计算属性的值 计算属性应该是只读的

六 组合API-watch-基本使用和立即执行

watch函数 image.png

  • 作用:侦听一个或者多个数据的变化,数据变化时执行回调函数
  • 倆个额外参数:
  • 1 immediate(立即执行)
  • 2 deep (深度侦听)

1 基础使用-侦听单个数据

  • 1 导入watch函数
  • 2 执行watch函数传入侦听的响应式数据(ref对象)和回调函数
  • 代码:
<script setup >
   import { ref, watch } from 'vue'
   const count = ref(0)
   const setCount = () => {
    count.value++
   }



   //watch 单个数据源
   // ref对象不需要加.value
   watch(count,(newVal,oldVal) => {
    console.log('count变化了',newVal,oldVal);
   })
  

</script>

<template>
<div>
  <button @click="setCount">+{{ count }}</button>
</div>
</template>

image.png

2 基础使用-侦听多个数据

image.png

<!-- 开关: 容许在script书写组合式API -->
<script setup >
   import { ref, watch } from 'vue'
   const count = ref(0)
   const setCount = () => {
    count.value++
   }

   const name = ref('cp')
   const changeName = () => {
    name.value = 'pc'
   }

   //watch 侦听多个数据源
   watch(
    [count,name],
    (
      [newCount,newName],
      [oldCount,oldName]
    ) =>{
      console.log('count或者name变化了', [newCount,newName],
      [oldCount,oldName])
    }
  )
</script>

<template>
<div>
  <button @click="setCount">+{{ count }}</button>
</div>
<div>
  <button @click="changeName">修改count--{{ count }}</button>
</div>
</template>

3 immediate

  • 说明: 在侦听器创建时立即触发回调,响应式数据变化之后继续执行回调
<script setup >
   import { ref, watch } from 'vue'
   const count = ref(0)
   const setCount = () => {
    count.value++
   }


   watch(count,() => {
    console.log('count数据变化了')
   },{
    immediate:true
   })

  

</script>

<template>
<div>
  <button @click="setCount">+{{ count }}</button>
</div>
</template>

4 deep

默认机制: 通过watch监听的ref对象默认是浅层侦听的,直接修改嵌套的对象属性不会触发回调执行,需要开启deep选项

<!-- 开关: 容许在script书写组合式API -->
<script setup >
   import { ref, watch } from 'vue'
   const state = ref({count:0 ,age:20})
   const setCount = () => {
    state.value.count++
   }


   watch(state,() => {
    console.log('count数据变化了')
   },{
    deep :true
   })

  

</script>

<template>
<div>
  {{ state.count }}
  <button @click="setCount">+{{ state }}</button>
</div>
</template>



5 精确侦听对象的某个属性

需求: 在不开启deep的前提下,侦听age的变化,只有age变化时才执行回调

<!-- 开关: 容许在script书写组合式API -->
<script setup >
   import { ref, watch } from 'vue'
   const state = ref({
    name:'chaichai',
    age:18
   })
  const changeName = () => {
    // 修改age
    state.value.name = 'chaichai-teacher'
  }

  const changAge = () => {
    
    state.value.age = 20
  }
   // 精确侦听某个具体对象
  watch(()=> state.value.age,
  ()=>{
    console.log('age变化了')
  })
  // deep 性能损耗 尽量不开启deep

</script>

<template>
<div>
    <div>当前name -- {{ state.name }}</div>
    <div>当前age -- {{ state.age }}</div>
    <div>
      <button @click="changeName">修改name</button>
      <button @click="changAge">修改age</button>
    </div>
</div>
</template>

总结:

  1. 作为watch的第一个参数,ref对象需要添加 .value吗?
  • 不需要,watch会自动读取
  1. watch只能侦听单个数据吗?
  • 单个或者多个
  1. 不开启deep,直接修改嵌套属性能触发回调吗?
  • 不能,默认是浅层侦听
  1. 不开启deep,想在某个层次比较深的属性变化时执行回调怎么做?
  • 可以把第一个参数写成函数的写法,返回要监听的具体属性

七 组合式API下的父子通信

1 父传子

  • 基本思想
  • 1 父组件中给子组件绑定属性
  • 2 子组件内部通过props选项接收

image.png

<!-- 开关: 容许在script书写组合式API -->
<script setup >
import { ref } from 'vue'
import SonCom from './son-con.vue'
const count = ref(100)
setTimeout(()=>{
  count.value = 200
},3000)

</script>

<template>
<div class="father">
  <h2>父组件APP</h2>
      <SonCom :count="count" message="father message"/>
</div>
</template>


<style scoped>

</style>
<script setup>
  const props = defineProps({
    message: String,
    count:Number
  })
  console.log(props)
</script>

<template>
  <div class="son">
    <h3>子组件Son</h3>
    <div>
      父组件传入的数据 - {{ message }} - {{ count }}
    </div>
  </div>
</template>

<style scoped>

</style>

2 子传父

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

image.png

代码:

<!-- 开关: 容许在script书写组合式API -->
<script setup >
import SonCom from './son-com.vue'
const getMessage = (msg) => {
  console.log(msg)
}
</script>

<template>
<div class="father">
  <h2>父组件APP</h2>
        <!-- 1 绑定事件 -->
      <SonCom  @get-message="getMessage"/>
</div>
</template>


<style scoped>

</style>

<script setup>
//  2 通过defineEmits() => emit(this.$emit)
const emit = defineEmits(['get-message'])
const sendMsg = () => {
    // 自定义组件
    //  触发自定义事件 传数据父组件
    emit('get-message','this is son message')
}
</script>

<template>
  <div class="son">
    <div>子组件Son</div>
    <button @click="sendMsg">自定义组件</button>
  </div>
</template>

- 总结:

- 父传子

  1. 父传子的过程中通过什么方式接收props?
  • defineProps({属性名: 类型})
  1. setup语法糖中如何使用父组件传过来的数据?
  • const props = defineprops({属性名: 类型})

- 子传父

1.子传父的过程中通过什么方式得到emit方法

  • defineEmits({'事件名称'})

八 模版引用

  • 模版引用概念

  • 通过ref标识获取真实的dom对象或者组件实例对象

  • 如何获取(以获取dom为例 组件同理)

  1. 调用ref函数生成一个ref对象
  2. 通过ref标识绑定ref对象到标签
<!-- 开关: 容许在script书写组合式API -->
<script setup >
    import TestCom from './test-com.vue'
    import { onMounted ,ref } from 'vue'


    // 1 调用ref函数 -> ref对象
    const h1Ref = ref(null)
    const comRef = ref(null)

    //组件挂载完毕之后才能获取
    onMounted(() => {
      console.log(h1Ref.value)
      console.log(comRef.value)
    })
</script>

<template>
   <h1 ref="h1Ref">我是dom标签h1</h1>
   <TestCom ref="comRef" />
</template>


<style scoped>

</style>
<script setup>
import { ref } from 'vue'

const name = ref('test name')
const setName = () => {
  name.value = 'test new name'
}

defineExpose({
  name,setName
})
</script>

<template>
  <div>我是test组件</div>
</template>
  • defineExpose()
  • 默认情况下在script setup语法糖下组件内部的属性和方法是不开放给父组件访问的,可以通过defineExpose编译宏指定哪些属性和方法允许访问

总结:

  1. 获取模版引用的时机是什么? 组件挂机完毕 2.defineExpose编译宏的作用是什么? 显示暴露组件内部的属性和方法

九 组合式API-provide和inject

  • 作用和场景
  • 顶层组件向任意的是底层组件传递数据和方法,实现跨层组件通信

1 跨层传递普通数据

  1. 顶层组件通过provide函数提供数据
  2. 底层组件通过inject函数获取数据

顶层组件 provide('key',顶层组件中的数据)

底层组件 const message = inject('key')

image.png

2 跨层传递方法

顶层组件可以向底层传递方法,底层组件调用方法修改顶层组件中的数据

image.png

<script setup>
import { provide ,ref } from 'vue'
import RoomMsgItem from './room-msg-comment.vue'
// 组件嵌套关系:
// RoomPage -> RoomMsgItem -> RommMsgComment

//  1 顶层组件提供数据
provide('data-key','this is room data')

// 传递响应式数据
const count = ref(0)
provide('count-key',count)
setTimeout(() => {
   count.value = 100
}, 3000)

// 传递方法
const setCount = () => {
  count.value++
}

provide('setCount-key',setCount)
</script>

<template>
  <div class="page">
    顶层组件
    <RoomMsgItem />
  </div>
</template>

<style scoped>
</style>



<script setup>
import { inject  } from 'vue'

// 2 接收数据
const roomData = inject('data-key')

// 接收响应式数据
const countData = inject('count-key')

// 接收方法
const setCount = inject('setCount-key')
</script>

<template>
  <div class="comment">
    底层组件
    <div>
      来自顶层组件中的数据为: {{ roomData }}
    </div>
    <div>
      来自顶层组件的响应式数据: {{ countData }}
    </div>
    <div>
      <button @click="setCount">修改顶层组件的数据:{{ setCount  }}</button>
    </div>
  </div>
</template>

总结

  1. provide和inject的作用是什么?
  • 跨层组件通信
  1. 如何在传递的过程中保存数据响应式?
  • 第二个参数传递ref对象
  1. 底层组件响应通知顶层组件做修改,如何做?
  • 传递方法,底层组件调用方法
  1. 一颗组件树中只有一个顶层或底层组件吗?
  • 相对概念,存在多个顶层和底层的关系

Vue3综合小案例

案例前置说明 项目地址 git clone git.itcast.cn/heimaqiandu…

  1. 模版已经配置好了案例必须的安装包
  2. 案例用到的接口在 README.MD文件中
  3. 案例项目有俩个分支,main主分支为开发分支,complete分支为完成版分支开发参考

代码:思路

<script setup>
import Edit from './components/Edit.vue'
import { onMounted,ref } from 'vue'
import axios  from 'axios';

// TODO: 列表渲染
// 思路:声明响应式list -> 调用接口获取数据 -> 后端数据赋值给list -> 绑定到table组件
const list = ref([])
const getList = async () => {
  //接口调用
const res = await  axios.get('/list')
// 交给list
list.value = res.data

}
onMounted(() => getList())
// TODO: 删除功能
// 思路: 获当前行的id -> 通过id通用删除接口 -> 更新最新的列表
const onDelete = async (id) => {
  console.log(id)
  await axios.delete(`/del/${id}`)
  getList()
}


// TODO: 编辑功能
// 思路 打开弹框 -> 回填数据 -> 更新数据
//1  打开弹框(获取子组件实例 调用方法或者修改属性)
//2  回填数据(调用详情接口 / 当前行的静态数据) 
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>

<script setup>
// TODO: 编辑
import { ref } from 'vue'
import axios from 'axios'
// 弹框开关
const dialogVisible = ref(false)
// 准备form
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 () => {
  // 1 收集表单数据,调用接口
  await axios.patch(`/edit/${form.value.id}`, {
  name: form.value.name,
  place: form.value.place ,
})
  // 2 关闭弹窗
  dialogVisible.value = false
  // 3 通知父组件做列表更新
   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>