VUE3学习笔记


前言

用于记录在b站学习尚硅谷vue3课程的笔记
免责声明:笔记由尚硅谷分享的md文件改编成适合自己阅读的样式,人家的md文件做的确实很不错,同时编辑一遍加强个人的印象,大体内容来自源文件,避免保存本地丢失,所以上传至CSDN,如果侵权联系删除


一、核心语法

1.1 OptionsAPI 与 CompositionAPI

Options API 的弊端

  • Vue2API设计是Options(配置)风格的。
  • Vue3API设计是Composition(组合)风格的。

Options类型的 API,数据、方法、计算属性等,是分散在:datamethodscomputed中的,若想新增或者修改一个需求,就需要分别修改:datamethodscomputed,不便于维护和复用。
1.gif 1.gif

Composition API 的优势

可以用函数的方式,更加优雅的组织代码,让相关功能的代码更加有序的组织在一起。
1.gif 1.gif

说明:以上四张动图原创作者:大帅老猿

1.2 setup

  • setup函数返回的对象中的内容,可直接在模板中使用。
  • setup中访问thisundefined
  • setup函数会在beforeCreate之前调用,它是“领先”所有钩子(其他生命周期)执行的,所以Vue2 的配置(datamethos…)中可以访问到 setup中的属性、方法,但在setup不能访问到Vue2的配置(datamethos…)。
  • 如果与Vue2冲突,则setup优先。
setup(){
     // 数据,原来写在data中(注意:此时的name数据不是响应式数据)
     let name = '张三'
     // 方法,原来写在methods中
     function changeName(){
       name = 'zhang-san' //注意:此时这么修改name页面是不变化的
       console.log(name)
     }
     // 返回一个对象,对象中的内容,模板中可以直接使用
     return {name,age,tel,changeName,changeAge,showTel}
   }
  • 若返回一个对象:则对象中的:属性、方法等,在模板中均可以直接使用(重点关注)
  • 若返回一个函数:则可以自定义渲染内容,代码如下:
setup(){
  return ()=> '你好啊!'
}

语法糖

可以直接使用定义的属性和方法,不需要手写return

<script setup lang="ts">
  // 数据(注意:此时的name不是响应式数据)
  let name = '张三'
  // 方法
  function changName(){
    name = '李四'//注意:此时这么修改name页面是不变化的
  }
</script>

1.3 ref

  • 作用: 定义响应式变量,可以是:基本类型对象类型
  • 语法:let xxx = ref(初始值)
  • 返回值: 一个RefImpl的实例对象,简称ref对象refref对象的value属性是响应式的
  • 注意点:
    • JS中操作数据需要:xxx.value,但模板中不需要.value,直接使用即可。
    • 对于let name = ref('张三')来说,name不是响应式的,name.value是响应式的。
    • ref接收的是对象类型,内部其实也是调用了reactive函数。
<script setup lang="ts">
  import {ref} from 'vue'
  // name是一个RefImpl的实例对象,简称ref对象,它们的value属性是响应式的。
  let name = ref('张三')
  // tel就是一个普通的字符串,不是响应式的
  let tel = '13888888888'
</script>

1.4 reactive

  • 作用:定义一个响应式对象(基本类型不要用它,要用ref,否则报错)
  • 语法:let 响应式对象= reactive(源对象)
  • 返回值: 一个Proxy的实例对象,简称:响应式对象。
  • 注意点:reactive定义的响应式数据是“深层次”的,重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)
<script setup lang="ts">
  import {reactive} from 'vue'
  let car = reactive({ brand: '奔驰', price: 100 })
  Object.assign(car, { brand: '宝马', price: 200 )
</script>

1.5 toRefs 与 toRef

  • 作用:将一个响应式对象中的每一个属性,转换为ref对象。
  • 备注:toRefstoRef功能一致,但toRefs可以批量转换。
<script lang="ts" setup>
  import {ref,reactive,toRefs,toRef} from 'vue'
  // 数据
  let person = reactive({name:'张三', age:18, gender:'男'})
  // 通过toRefs将person对象中的n个属性批量取出,且依然保持响应式的能力
  let {name,gender} =  toRefs(person)
  // 通过toRef将person对象中的gender属性取出,且依然保持响应式的能力
  let age = toRef(person,'age')
</script>

1.6 computed

<script lang="ts" setup>
  import {ref,computed} from 'vue'
  let firstName = ref('zhang')
  let lastName = ref('san')
  // 计算属性——只读取,不修改
  let fullName = computed(()=>{
    return firstName.value + '-' + lastName.value
  })
  // 计算属性——既读取又修改
  let fullName = computed({
    // 读取
    get(){
      return firstName.value + '-' + lastName.value
    },
    // 修改
    set(val){
      console.log('有人修改了fullName',val)
      firstName.value = val.split('-')[0]
      lastName.value = val.split('-')[1]
    }
  })
</script>

1.7 watch 和 watchEffect

  • 作用:监视数据的变化(和Vue2中的watch作用一致)
  • 特点:Vue3中的watch只能监视以下四种数据
  1. ref定义的数据。
  2. reactive定义的数据。
  3. 函数返回一个值(getter函数)。
  4. 一个包含上述内容的数组。

情况一:监视ref定义的【基本类型】数据

<script lang="ts" setup>
	import {ref,watch} from 'vue'
	// 数据
	let sum = ref(0)
	// 方法
	function changeSum(){
	  sum.value += 1
	}
	// 直接写数据名即可,监视的是其`value`值的改变
	const stopWatch = watch(sum,(newValue,oldValue)=>{
	  console.log('sum变化了',newValue,oldValue)
	  if(newValue >= 10){
	    stopWatch()	//  用于停止监听
	  }
	})
</script>

情况二:监视ref定义的【对象类型】数据

注意:

  • 若修改的是ref定义的对象中的属性,newValueoldValue 都是新值,因为它们是同一个对象。

  • 若修改整个ref定义的对象,newValue 是新值, oldValue 是旧值,因为不是同一个对象了。

<script lang="ts" setup>
	import {ref,watch} from 'vue'
	// 数据
	let person = ref({
	  name:'张三',
	  age:18
	})
	// 方法
	function changeName(){
	  person.value.name += '~'
	}
	function changePerson(){
	  person.value = {name:'李四',age:90}
	}
	// 监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视
	watch(person,(newValue,oldValue)=>{
	  console.log('person变化了',newValue,oldValue)
	},{deep:true})
</script>

情况三:监视reactive定义的【对象类型】数据

<script lang="ts" setup>
	import {reactive,watch} from 'vue'
	// 数据
	let person = reactive({
	  name:'张三',
	  age:18
	})
	// 方法
	function changeName(){
	  person.name += '~'
	}
	function changePerson(){
	  Object.assign(person,{name:'李四',age:80})
	}
	// 监视,情况三:监视【reactive】定义的【对象类型】数据,默认是开启深度监视的
	watch(person,(newValue,oldValue)=>{
	  console.log('person变化了',newValue,oldValue)
	})
</script>

情况四:监视refreactive定义的【对象类型】数据中的某个属性

注意:

  • 对象类型的,直接写相当于监听reactive定义的对象类型,默认是开启深度监视的,直接修改其本身会失去监听

  • 对象类型的,用函数写相当于监听ref定义的对象类型,修改其本身相当于修改他的.value,能监听到,内部属性需要开启深度监听

<script lang="ts" setup>
	import {reactive,watch} from 'vue'
	// 数据
	let person = reactive({
	  name:'张三',
	  age:18,
	  car:{
	    c1:'奔驰',
	    c2:'宝马'
	  }
	})
	// 方法
	function changeName(){
	  person.name += '~'
	}
	function changeC1(){
	  person.car.c1 = '奥迪'
	}
	function changeCar(){
	  person.car = {c1:'雅迪',c2:'爱玛'}
	}
	// 监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
	watch(()=> person.name,(newValue,oldValue)=>{
	  console.log('person.name变化了',newValue,oldValue)
	})
	// 监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
	watch(()=>person.car,(newValue,oldValue)=>{
	  console.log('person.car变化了',newValue,oldValue)
	},{deep:true})
</script>

情况五:监视上述的多个数据

<script lang="ts" setup>
	import {reactive,watch} from 'vue'
	// 数据
	let person = reactive({
	  name:'张三',
	  age:18,
	  car:{
	    c1:'奔驰',
	    c2:'宝马'
	  }
	})
	// 方法
	function changeName(){
	  person.name += '~'
	}
	function changeC1(){
	  person.car.c1 = '奥迪'
	}
	function changeCar(){
	  person.car = {c1:'雅迪',c2:'爱玛'}
	}
	// 监视,情况五:监视上述的多个数据
	watch([()=>person.name,person.car],(newValue,oldValue)=>{
	  console.log('person.car变化了',newValue,oldValue)
	},{deep:true})
</script>

watchEffect

  • 官网:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。

  • watch对比watchEffect

    1. 都能监听响应式数据的变化,不同的是监听数据变化的方式不同

    2. watch:要明确指出监视的数据

    3. watchEffect:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性)。

<script lang="ts" setup>
	import {ref,watch,watchEffect} from 'vue'
	// 数据
	let temp = ref(0)
	let height = ref(0)
	// 方法
	function changePrice(){
	  temp.value += 10
	}
	function changeSum(){
	  height.value += 1
	}
	// 用watch实现,需要明确的指出要监视:temp、height
	watch([temp,height],(value)=>{
	  // 从value中获取最新的temp值、height值
	  const [newTemp,newHeight] = value
	  // 室温达到50℃,或水位达到20cm,立刻联系服务器
	  if(newTemp >= 50 || newHeight >= 20){
	    console.log('联系服务器')
	  }
	})
	
	// 用watchEffect实现,不用
	const stopWtach = watchEffect(()=>{
	  // 室温达到50℃,或水位达到20cm,立刻联系服务器
	  if(temp.value >= 50 || height.value >= 20){
	    console.log(document.getElementById('demo')?.innerText)
	    console.log('联系服务器')
	  }
	  // 水温达到100,或水位达到50,取消监视
	  if(temp.value === 100 || height.value === 50){
	    console.log('清理了')
	    stopWtach()
	  }
	})
</script>

1.8 标签的 ref 属性

  • 用在普通DOM标签上,获取的是DOM节点。

  • 用在组件标签上,获取的是组件实例对象。

<template>
	<div class="person">
		<h1 ref="title1">尚硅谷</h1>
		<Person ref="ren"/>
		<button @click="showLog">点我打印内容</button>
	</div>
</template>

<script lang="ts" setup>
	import Person from './components/Person.vue'
	import {ref} from 'vue'
	
	let title1 = ref()
	let ren = ref()
	
	function showLog(){
	  // 通过ref获取元素
	  console.log(title1.value) // dom节点
	  console.log(ren.value)	// 组件实例
	}
</script>
  • 组件实例和vue2有区别,不能直接操作组件实例里面的属性和方法,要在组件中使用defineExpose暴露内容
<script lang="ts" setup name="Person">
	import {ref,defineExpose} from 'vue'
	// 数据
	let name = ref('张三')
	let age = ref(18)
	// 使用defineExpose将组件中的数据交给外部
	defineExpose({name,age})
</script>

1.9 props

// 定义一个接口,限制每个Person对象的格式
export interface PersonInter {
	id:string,
	name:string,
	age:number
}

// 定义一个自定义类型Persons
export type Persons = Array<PersonInter>

父组件

<template>
	<Person :list="persons"/>
</template>

<script lang="ts" setup name="App">
	import Person from './components/Person.vue'
	import {reactive} from 'vue'
	import {type Persons} from './types'

 let persons = reactive<Persons>([
	{id:'e98219e12',name:'张三',age:18},
	{id:'e98219e13',name:'李四',age:19},
	{id:'e98219e14',name:'王五',age:20}
  ])
</script>

子组件

<template>
<div class="person">
<ul>
  <li v-for="item in list" :key="item.id">
     {{item.name}}--{{item.age}}
   </li>
 </ul>
</div>
</template>

<script lang="ts" setup name="Person">
	import {defineProps, withDefaults} from 'vue'	// define开头的宏函数可以不用引入
	import {type PersonInter} from '@/types'
	
	// 第一种写法:仅接收
	const props = defineProps(['list'])
	
	// 第二种写法:接收+限制类型
	defineProps<{list:Persons}>()
	
	// 第三种写法:接收+限制类型+指定默认值+限制必要性
	let props = withDefaults(defineProps<{list?:Persons}>(),{
	  list:() => [{id:'asdasg01',name:'小猪佩奇',age:18}]
	})
	console.log(props)
</script>

1.10 生命周期

  • 概念:Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子
  • 规律:

    生命周期整体分为四个阶段,分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后。

  • Vue2的生命周期

创建阶段:beforeCreatecreated

挂载阶段:beforeMountmounted

更新阶段:beforeUpdateupdated

销毁阶段:beforeDestroydestroyed

  • Vue3的生命周期

创建阶段:setup

挂载阶段:onBeforeMountonMounted

更新阶段:onBeforeUpdateonUpdated

卸载阶段:onBeforeUnmountonUnmounted

  • 常用的钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)

1.11 自定义hooks

  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2中的mixin
  • 自定义hook的优势:复用代码, 让setup中的逻辑更清楚易懂。
// useSum.ts
import {ref,onMounted} from 'vue'
export default function(){
  let sum = ref(0)

  const increment = ()=>{
    sum.value += 1
  }
  const decrement = ()=>{
    sum.value -= 1
  }
  onMounted(()=>{
    increment()
  })

  //向外部暴露数据
  return {sum,increment,decrement}
}	

二、路由

2.1 路由基本配置

// router.ts
import {createRouter,createWebHistory} from 'vue-router'
import Home from '@/pages/Home.vue'

const router = createRouter({
	history:createWebHistory(),
	routes:[
		{
			name:'home',
			path:'/home',
			component:Home
		}
	]
})
export default router
// main.ts
import router from './router/index'
app.use(router)
app.mount('#app')
<template>
  <div class="app">
    <h2 class="title">Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
      <RouterLink to="/home" active-class="active">首页</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
  import {RouterLink,RouterView} from 'vue-router'  
</script>

2.2 路由工作模式

  1. history模式

    优点:URL更加美观,不带有#,更接近传统的网站URL

    缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误。

    const router = createRouter({
      	history:createWebHistory(), //history模式
      	/******/
    })
    
  2. hash模式

    优点:兼容性更好,因为不需要服务器端处理路径。

    缺点:URL带有#不太美观,且在SEO优化方面相对较差。

    const router = createRouter({
      	history:createWebHashHistory(), //hash模式
      	/******/
    })
    

2.3 to的两种写法

<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>

<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>

2.4 嵌套路由

  1. 编写News的子路由:Detail.vue

  2. 配置路由规则,使用children配置项:

    const router = createRouter({
      history:createWebHistory(),
    	routes:[
    		{
    			name:'zhuye',
    			path:'/home',
    			component:Home
    		},
    		{
    			name:'xinwen',
    			path:'/news',
    			component:News,
    			children:[
    				{
    					name:'xiang',
    					path:'detail',
    					component:Detail
    				}
    			]
    		},
    		{
    			name:'guanyu',
    			path:'/about',
    			component:About
    		}
    	]
    })
    export default router
    

2.5 路由传参

query参数

// 跳转并携带query参数(to的字符串写法)
<router-link to="/news/detail?a=1&b=2&content=欢迎你">
	跳转
</router-link>
				
// 跳转并携带query参数(to的对象写法)
<RouterLink 
  :to="{
    //name:'xiang', //用name也可以跳转
    path:'/news/detail',
    query:{
      id:news.id,
      title:news.title,
      content:news.content
    }
  }"
>
  {{news.title}}
</RouterLink>

params参数

// 跳转并携带params参数(to的字符串写法)
<RouterLink :to="`/news/detail/001/新闻001/内容001`">{{news.title}}</RouterLink>
				
// 跳转并携带params参数(to的对象写法)
<RouterLink 
  :to="{
    name:'xiang', //用name跳转
    params:{
      id:news.id,
      title:news.title,
      content:news.title
    }
  }"
>
  {{news.title}}
</RouterLink>

备注1:传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path

备注2:传递params参数时,需要提前在规则中占位。

{
	name:'xiang',
	path:'detail/:id/:title/:content?',	// 带?表示可选参数
	component:Detail,
}

接收参数

import {useRoute} from 'vue-router'
const route = useRoute()
// 打印query参数
console.log(route.query)

props配置

{
	name:'xiang',
	path:'detail/:id/:title/:content',
	component:Detail,
	
	// props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
	props:{a:1,b:2,c:3}, 
	
	// props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
	props:true
	
	// props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
	props(route){
	  return route.query
	}	
}

props的写法相当于往子组件<Detail />上传递props,用接收props的方式defineProps接收参数

2.6 replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式。

  2. 浏览器的历史记录有两种写入方式:分别为pushreplace

    • push是追加历史记录(默认值)。
    • replace是替换当前记录。
  3. 开启replace模式:

<RouterLink replace .......>News</RouterLink>

2.7 重定向

  1. 作用:将特定的路径,重新定向到已有路由。

  2. 具体编码:

{
    path:'/',
    redirect:'/about'
}

三、pinia

3.1 搭建pinia环境

import { createApp } from 'vue'
import App from './App.vue'

/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'

/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)

/* 使用插件 */{}
app.use(pinia)
app.mount('#app')

3.2 引用并创建store

  1. Store是一个保存:状态业务逻辑 的实体,每个组件都可以读取写入它。
  2. 它有三个概念:stategetteraction,相当于组件中的: datacomputedmethods
// 定义一个store文件 count.ts
// 引入defineStore用于创建store
import {defineStore} from 'pinia'

// 定义并暴露一个store
export const useCountStore = defineStore('count',{
  // 动作
  actions:{},
  // 状态
  state(){
    return {
      sum:6
    }
  },
  // 计算
  getters:{}
})
<template>
	<h2>当前求和为:{{ countStore.sum }}</h2>
</template>

<script setup lang="ts">
// 引入对应的useXxxxxStore	
import { useCountStore } from '@/store/count'

// 调用useXxxxxStore得到对应的store
const countStore = useCountStore ()
</script>

3.3 读取 + 修改数据

读取数据

<template>
	<h2>当前求和为:{{ countStore.sum }}</h2>
</template>

<script setup lang="ts">
// 引入对应的useXxxxxStore	
import { useCountStore } from '@/store/count'

// 调用useXxxxxStore得到对应的store
const countStore = useCountStore ()
console.log(countStore.sum)
console.log(countStore.$state.sum)
</script>

修改数据

import { defineStore } from 'pinia'

export const useCountStore = defineStore('count', {
  actions: {
    //加
    increment(value:number) {
      if (this.sum < 10) {
        //操作countStore中的sum
        this.sum += value
      }
    },
    //减
    decrement(value:number){
      if(this.sum > 1){
        this.sum -= value
      }
    }
  }
})
<script setup lang="ts">
// 引入对应的useXxxxxStore	
import { ref} from 'vue'
import { useCountStore } from '@/store/count'
// 调用useXxxxxStore得到对应的store
const countStore = useCountStore ()

// 方法一:直接修改
countStore.sum = 666
// 方法二:批量修改
countStore.$patch({
  sum:999,
  school:'atguigu'
})
// 方法三:借助action修改,
let n = ref(1)
countStore.incrementOdd(n.value)
</script>

3.4 getters

// 引入defineStore用于创建store
import {defineStore} from 'pinia'

// 定义并暴露一个store
export const useCountStore = defineStore('count',{
  // 动作
  actions:{

  },
  // 状态
  state(){
    return {
      sum:1,
      school:'atguigu'
    }
  },
  // 计算
  getters:{
    bigSum:(state):number => state.sum *10,
    upperSchool():string{
      return this. school.toUpperCase()
    }
  }
})

3.5 storeToRefs

  • 借助storeToRefsstore中的数据转为ref对象,方便在模板中使用。
  • 注意:pinia提供的storeToRefs只会将数据做转换,而VuetoRefs会转换整个store
<script setup lang="ts" name="Count">
import { useCountStore } from '@/store/count'
/* 引入storeToRefs */
import { storeToRefs } from 'pinia'

/* 得到countStore */
const countStore = useCountStore()
/* 使用storeToRefs转换countStore,随后解构 */
const {sum} = storeToRefs(countStore)
</script>

3.6 $subscribe

通过 store 的 $subscribe() 方法侦听 state 及其变化

countStore .$subscribe((mutate,state)=>{
  
})

3.7 store组合式写法

import {defineStore} from 'pinia'
import {ref} from 'vue'

export const useCountStore = defineStore('count',()=>{
  // sum就是state
  const sum = ref(1)

  // addSum函数相当于action
  function addSum(){
    sum += 1
  }
  return {sum,addSum}
})

四、组件通信

Vue3组件通信和Vue2的区别:

  • 移除事件总线,使用mitt代替。
  • vuex换成了pinia
  • .sync优化到了v-model里面了。
  • $listeners所有的东西,合并到$attrs中了。
  • $children被砍掉了。

4.1 props

props是使用频率最高的一种通信方式,常用与 父 ↔ 子组件之间

  • 父传子:属性值是非函数
  • 子传父:属性值是函数
// 父组件
<template>
  <div class="father">
    <h3>父组件,</h3>
	<h4>我的车:{{ car }}</h4>
	<h4>儿子给的玩具:{{ toy }}</h4>
	<Child :car="car" :getToy="getToy"/>
  </div>
</template>

<script setup lang="ts" name="Father">
	import Child from './Child.vue'
	import { ref } from "vue";
	// 数据
	const car = ref('奔驰')
	const toy = ref()
	// 方法
	function getToy(value:string){
		toy.value = value
	}
</script>
// 子组件
<template>
  <div class="child">
    <h3>子组件</h3>
	<h4>我的玩具:{{ toy }}</h4>
	<h4>父给我的车:{{ car }}</h4>
	<button @click="getToy(toy)">玩具给父亲</button>
  </div>
</template>

<script setup lang="ts" name="Child">
	import { ref } from "vue";
	const toy = ref('奥特曼')
	defineProps(['car','getToy'])
</script>

4.2 自定义事件

自定义事件常用于:子 => 父。

  • 原生事件:
    • 事件名是特定的(clickmosueenter等等)
    • 事件对象$event: 是包含事件相关信息的对象(pageXpageYtargetkeyCode
  • 自定义事件:
    • 事件名是任意名称
    • 事件对象$event: 是调用emit时所提供的数据,可以是任意类型!!!
// 在父组件中,给子组件绑定自定义事件
<Child @send-toy="toy = $event"/>
// 注意区分原生事件与自定义事件中的$event
//子组件中,触发事件:
const emit = defineEmits(['send-toy'])
emit('send-toy', 具体数据)

4.3 mitt

概述:与消息订阅与发布(pubsub)功能类似,可以实现任意组件间通信。

安装mitt

npm i mitt

新建文件:src\utils\emitter.ts

// 引入mitt 
import mitt from "mitt";

// 创建emitter
const emitter = mitt()

// 暴露mitt
export default emitter
import emitter from "@/utils/emitter";
import { onUnmounted } from "vue";

// 绑定事件
emitter.on('send-toy',(value)=>{
  console.log('send-toy事件被触发',value)
})

// 触发事件
emitter.emit('send-toy',777)

onUnmounted(()=>{
  // 解绑事件
  emitter.off('send-toy')
  // 清理全部事件
  emitter.all.clear()
})

4.4 v-model

实现 父↔子 之间相互通信

前序知识 ——v-model的本质

// 使用v-model指令
<input type="text" v-model="userName">

// v-model的本质是下面这行代码
<input 
  type="text" 
  :value="userName" 
  @input="userName =(<HTMLInputElement>$event.target).value"
>

组件标签上的v-model的本质::moldeValueupdate:modelValue事件。

// 组件标签上使用v-model指令
<AtguiguInput v-model="userName"/>

// 组件标签上v-model的本质
<AtguiguInput :modelValue="userName" @update:model-value="userName = $event"/>

AtguiguInput组件中:

<template>
  <div class="box">
    // 将接收的value值赋给input元素的value属性,目的是:为了呈现数据
	// 给input元素绑定原生input事件,触发input事件时,进而触发update:model-value事件
    <input 
       type="text" 
       :value="modelValue" 
       @input="emit('update:model-value',$event.target.value)"
    >
  </div>
</template>

<script setup lang="ts" name="AtguiguInput">
  // 接收props
  defineProps(['modelValue'])
  // 声明事件
  const emit = defineEmits(['update:model-value'])
</script>

可以通过更改绑定的value,实现多个v-model

// 更换value,例如改成abc
<AtguiguInput v-model:abc="userName"/>

// 上面代码的本质如下
<AtguiguInput :abc="userName" @update:abc="userName = $event"/>
// AtguiguInput 组件
<template>
  <div class="box">
    <input 
       type="text" 
       :value="abc" 
       @input="emit('update:abc',$event.target.value)"
    >
  </div>
</template>

<script setup lang="ts" name="AtguiguInput">
  // 接收props
  defineProps(['abc'])
  // 声明事件
  const emit = defineEmits(['update:abc'])
</script>
<AtguiguInput v-model:abc="userName" v-model:xyz="password"/>

4.5 $attrs

  1. 概述:$attrs用于实现当前组件的父组件,向当前组件的子组件通信(祖→孙)。

  2. 具体说明:$attrs是一个对象,包含所有父组件传入的标签属性。

    注意:$attrs会自动排除props中声明的属性(可以认为声明过的 props 被子组件自己“消费”了)

<template>
	<div class="father">
		<h3>父组件</h3>
		<Child :a="a" :b="b" v-bind="{x:100,y:200}" :updateA="updateA"/>
	</div>
</template>

<script setup lang="ts" name="Father">
	import Child from './Child.vue'
	import { ref } from "vue";
	let a = ref(1)
	let b = ref(2)
	
	function updateA(value){
		a.value = value
	}
</script>
<template>
	<div class="child">
		<h3>子组件</h3>
		<GrandChild v-bind="$attrs"/>
	</div>
</template>

<script setup lang="ts" name="Child">
	import GrandChild from './GrandChild.vue'
</script>
<template>
	<div class="grand-child">
		<h3>孙组件</h3>
		<h4>a:{{ a }}</h4>
		<h4>b:{{ b }}</h4>
		<h4>x:{{ x }}</h4>
		<h4>y:{{ y }}</h4>
		<button @click="updateA(666)">点我更新A</button>
	</div>
</template>

<script setup lang="ts" name="GrandChild">
	defineProps(['a','b','c','d','x','y','updateA'])
</script>

4.6 $refs 和 $parent

  • $refs用于 :父→子。

  • $parent用于:子→父。

    属性说明
    $refs值为对象,包含所有被ref属性标识的DOM元素或组件实例。
    $parent值为对象,当前组件的父组件实例对象。
// 在父组件中获取子组件的数据
<template>
	<div class="father">
		<h3>父组件</h3>
		<Child ref="child"/>
		<button @click="getRefs($refs)"></button>
	</div>
</template>

<script setup lang="ts" name="Father">
	import Child from './Child.vue'
	import { ref } from "vue";
	let a = ref(1)
	let child = ref()
	console.log(child.value.a)
	function getRefs(refs:{[key:string]:any}) {
		console.log(refs['child'].value.a)
	}
	defineExpose({a})
</script>
<template>
	<div class="father">
		<h3>子组件</h3>
		<button @click="getParent($parent)"></button>
	</div>
</template>

<script setup lang="ts" name="Child">
	import { ref } from "vue";
	let a= ref(1)
	function getParent(parent:any) {
		console.log(parent.a)
	}
	// 组件需要将数据暴露出去,才能通过$refs获取
	defineExpose({a})
</script>

4.7 provide 和 inject

实现祖孙组件直接通信

  • 在祖先组件中通过provide配置向后代组件提供数据
  • 在后代组件中通过inject配置来声明接收数据
<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>资产:{{ money }}</h4>
    <h4>汽车:{{ car }}</h4>
    <button @click="money += 1">资产+1</button>
    <button @click="car.price += 1">汽车价格+1</button>
    <Child/>
  </div>
</template>

<script setup lang="ts" name="Father">
  import Child from './Child.vue'
  import { ref,reactive,provide } from "vue";
  // 数据
  let money = ref(100)
  let car = reactive({
    brand:'奔驰',
    price:100
  })
  // 用于更新money的方法
  function updateMoney(value:number){
    money.value += value
  }
  // 提供数据
  provide('moneyContext',{money,updateMoney})
  provide('car',car)
</script>
<template>
  <div class="grand-child">
    <h3>我是孙组件</h3>
    <h4>资产:{{ money }}</h4>
    <h4>汽车:{{ car }}</h4>
    <button @click="updateMoney(6)">点我</button>
  </div>
</template>

<script setup lang="ts" name="GrandChild">
  import { inject } from 'vue';
  // 注入数据
  // 防止拿不到数据,可以设置默认值
  let {money,updateMoney} = inject('moneyContext',{money:0,updateMoney:(x:number)=>{}})
  let car = inject('car')
</script>

4.8 slot 插槽

默认插槽

// 父组件:
<Category title="今日热门游戏">
  <ul>
    <li v-for="g in games" :key="g.id">{{ g.name }}</li>
  </ul>
</Category>
// 子组件:
<template>
  <div class="item">
    <h3>{{ title }}</h3>
    <!-- 默认插槽 -->
    <slot></slot>
  </div>
</template>

具名插槽

// 父组件:
<Category title="今日热门游戏">
  <template v-slot:s1>
    <ul>
      <li v-for="g in games" :key="g.id">{{ g.name }}</li>
    </ul>
  </template>
  <template #s2>
    <a href="">更多</a>
  </template>
</Category>
// 子组件:
<template>
  <div class="item">
    <h3>{{ title }}</h3>
    <slot name="s1"></slot>
    <slot name="s2"></slot>
  </div>
</template>

作用域插槽

数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定

// 父组件:
<Game v-slot="params">
// <Game v-slot:default="params">
// <Game #default="params">
  <ul>
    <li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
  </ul>
</Game>

子组件中:
<template>
  <div class="category">
    <h2>今日游戏榜单</h2>
    <slot :games="games" a="哈哈"></slot>
  </div>
</template>

<script setup lang="ts" name="Category">
  import {reactive} from 'vue'
  let games = reactive([
    {id:'asgdytsa01',name:'英雄联盟'},
    {id:'asgdytsa02',name:'王者荣耀'},
    {id:'asgdytsa03',name:'红色警戒'},
    {id:'asgdytsa04',name:'斗罗大陆'}
  ])
</script>

五、其他API

5.1 shallowRef 与 shallowReactive

shallowRef:创建一个响应式数据,但只对顶层属性进行响应式处理
shallowReactive:创建一个浅层响应式对象,只会使对象的最顶层属性变成响应式的,对象内部的嵌套属性则不会变成响应式的

通过使用 shallowRef()shallowReactive() 来绕开深度响应。浅层式 API 创建的状态只在其顶层是响应式的,对所有深层的对象不会做任何处理,避免了对每一个内部属性做响应式所带来的性能成本,这使得属性的访问变得更快,可提升性能。

<script setup lang="ts">
	import {shallowRef,shallowReactive} from 'vue'
	let a = shallowRef(1)	// 具备响应式
	let b = shallowRef({a:1})	//b具备响应式,b.value.a不具备响应式
	let c = shallowReactive({a:1})	//c具备响应式,c.a不具备响应式
</script>

5.2 readonly 与 shallowReadonly

readonly:用于创建一个对象的深只读副本

  • 对象的所有嵌套属性都将变为只读
  • 任何尝试修改这个对象的操作都会被阻止(在开发模式下,还会在控制台中发出警告)
const original = reactive({ ... });		// 可以进行修改
const readOnlyCopy = readonly(original);	// 不能进行修改

shallowReadonly:与 readonly 类似,但只作用于对象的顶层属性

  • 只将对象的顶层属性设置为只读,对象内部的嵌套属性仍然是可变的
const original = reactive({ ... });	// 可以进行修改
const shallowReadOnlyCopy = shallowReadonly(original);	// 顶层引用地址不能修改,里面的值可以

5.3 toRaw 与 markRaw

toRaw:用于获取一个响应式对象的原始对象, toRaw 返回的对象不再是响应式的,不会触发视图更新

官网描述:这是一个可以用于临时读取而不引起代理访问/跟踪开销,或是写入而不触发更改的特殊方法。不建议保存对原始对象的持久引用,请谨慎使用。

何时使用? —— 在需要将响应式对象传递给非 Vue 的库或外部系统时,使用 toRaw 可以确保它们收到的是普通对象

import { reactive,toRaw} from "vue";

/* toRaw */
// 响应式对象
let person = reactive({name:'tony',age:18})
// 原始对象
let rawPerson = toRaw(person)

console.log(isReactive(person))	// true
console.log(isReactive(rawPerson))	// false

markRaw:标记一个对象,使其永远不会变成响应式的

 let citys = markRaw([
  {id:'asdda01',name:'北京'},
  {id:'asdda02',name:'上海'},
  {id:'asdda03',name:'天津'},
  {id:'asdda04',name:'重庆'}
])
// 根据原始对象citys去创建响应式对象citys2 —— 创建失败,因为citys被markRaw标记了
let citys2 = reactive(citys)

5.4 customRef

创建一个自定义的ref,并对其依赖项跟踪和更新触发进行逻辑控制
实现防抖效果(useSumRef.ts

import {customRef } from "vue";

export default function(initValue:string,delay:number){
  let msg = customRef((track,trigger)=>{
    let timer:number
    return {
      get(){
        track() // 告诉Vue数据msg很重要,要对msg持续关注,一旦变化就更新
        return initValue
      },
      set(value){
        clearTimeout(timer)
        timer = setTimeout(() => {
          initValue = value
          trigger() //通知Vue数据msg变化了
        }, delay);
      }
    }
  }) 
  return {msg}
}
// 组件中使用
<script setup lang="ts">
	import {useSumRef} from './useSumRef'
	let {msg} = useSumRef('xxx', 2000)
</script>
  • 30
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值