总结(尚硅谷Vue3入门到实战,最新版vue3+TypeScript前端开发教程)

1.Vue简介

2020年9月18日,Vue.js发布版3.0版本,代号:One Piece

1.1.性能的提升

        打包大小减少41%

        初次渲染快55%, 更新渲染快133%

        内存减少54%

1.2.源码的升级

        使用Proxy代替defineProperty实现响应式。

         重写虚拟DOM的实现和Tree-Shaking

1.3.拥抱TypeScript

  Vue3可以更好的支持TypeScript

1.4 新的特性

        ref和reactive

        新的生命周期函数

2.创建Vue3工程

基于 vite 创建(推荐)

## 1.创建命令
npm create vue@latest## 2.具体配置
## 配置项目名称
√ Project name: vue3_test
## 是否添加TypeScript支持
√ Add TypeScript?  Yes
## 是否添加JSX支持
√ Add JSX Support?  No
## 是否添加路由环境
√ Add Vue Router for Single Page Application development?  No
## 是否添加pinia环境
√ Add Pinia for state management?  No
## 是否添加单元测试
√ Add Vitest for Unit Testing?  No
## 是否添加端到端测试方案
√ Add an End-to-End Testing Solution? » No
## 是否添加ESLint语法检查
√ Add ESLint for code quality?  Yes
## 是否添加Prettiert代码格式化
√ Add Prettier for code formatting?  No

3.Vue3核心语法

3.1.OptionsAPI 与 CompositionAPI

        Vue2的APi设计是Options(配置)风格,Vue3则是Composition(组合)风格,让相关功能的代码更加有序的组合在一起

3.2.setup

概述

注意:setup函数中访问this是undefined

           所有值和函数都可以定义到setup函数中,但需要通过return“交出去”出来让外界使用

<template><div class="person"><h2>姓名:{{name}}</h2><h2>年龄:{{age}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">年龄+1</button><button @click="showTel">点我查看联系方式</button></div>
</template><script lang="ts">export default {name:'Person',setup(){// 数据,原来写在data中(注意:此时的name、age、tel数据都不是响应式数据)let name = '张三'let age = 18let tel = '13888888888'// 方法,原来写在methods中function changeName(){name = 'zhang-san' //注意:此时这么修改name页面是不变化的console.log(name)}function changeAge(){age += 1 //注意:此时这么修改age页面是不变化的console.log(age)}function showTel(){alert(tel)}// 返回一个对象,对象中的内容,模板中可以直接使用return {name,age,tel,changeName,changeAge,showTel}}}
</script>

 setup返回值

如果时返回一个对象则正常被调用

如果返回是一个函数,则会自动挂载,无关模板

setup(){return ()=> '你好啊!'
}

setup语法糖

 一般来说需要使用vite插件简化

step1:npm i vite-plugin-vue-setup-extend -D

step2:修改vite.config.ts

import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'export default defineConfig({plugins: [ VueSetupExtend() ]
})

step3:直接<script setup lang="ts" name="Person">

3.3.ref 创建:基本类型的响应式数据

 import {ref} from 'vue'

语法:let age = ref(初始值),

返回值:是RefImpl的实例对象,简称ref对象,ref对象的value属性是响应式的

注意

        1.js中操作响应式对象需要用 xx.value ,在模板中直接用即可,无需.value

        2.对于 let age = ref(18)来说,age不是响应式的,age.value是响应式的

3.4.reactive 创建:对象类型的响应式数据

import { reactive } from 'vue'

语法:iet 响应式对象 = reactive(源对象)

返回值:proxy的实例对象,简称响应式对象

注意.reactive不能定义基本数据类型

3.5.ref 创建:对象类型的响应式数据

ref接收的是对象类型,内部其实也是调用了reactive函数。

注意:调用对象的属性应该是    xx.value.属性

代码能证明一切

<template><div class="person"><h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2><h2>游戏列表:</h2><ul><li v-for="g in games" :key="g.id">{{ g.name }}</li></ul><h2>测试:{{obj.a.b.c.d}}</h2><button @click="changeCarPrice">修改汽车价格</button><button @click="changeFirstGame">修改第一游戏</button><button @click="test">测试</button></div>
</template><script lang="ts" setup name="Person">
import { ref } from 'vue'// 数据
let car = ref({ brand: '奔驰', price: 100 })
let games = ref([{ id: 'ahsgdyfa01', name: '英雄联盟' },{ id: 'ahsgdyfa02', name: '王者荣耀' },{ id: 'ahsgdyfa03', name: '原神' }
])console.log(car)function changeCarPrice() {car.value.price += 10
}
function changeFirstGame() {games.value[0].name = '流星蝴蝶剑'
}
function test(){obj.value.a.b.c.d = 999
}
</script>

3.6.ref 对比 reactive

使用原则:

  1. 若需要一个基本类型的响应式数据,必须使用ref
  2. 若需要一个响应式对象,层级不深,refreactive都可以。
  3. 若需要一个响应式对象,且层级较深,推荐使用reactive

注意:reactive重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)

let stu = reactive({name:'张三',age:18})stu = {name:'王五',age:19}//这样会失去响应式,//可以使用Object.assign整体替换
Object.assign(stu,{'王五' ,19})

3.7 toRefs 与 toRef

作用:将一个响应式对象中的所有属性转化为ref对象

注意:toRefstoRef功能一致,但toRefs可以批量转换。

<template><div class="person"><h2>姓名:{{person.name}}</h2><h2>年龄:{{person.age}}</h2><h2>性别:{{person.gender}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">修改年龄</button><button @click="changeGender">修改性别</button></div>
</template><script lang="ts" setup name="Person">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')// 方法function changeName(){name.value += '~'}function changeAge(){age.value += 1}function changeGender(){gender.value = '女'}
</script>

3.8.computed

只有待计算的值发生改变,computed才可以重新计算一次(比较聪明)

默认计算的值是只读的,只有当写上get()和set()方法,计算出来的值才是可读可写的


<script setup lang="ts" name="App">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]}})//因为前面有了set方法,所以现在可读可写fullName.vaule = 'li-si'</script>

3.9. watch

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

监视函数watch中直接写基本类型,无需加 ‘.value’

<template><div class="watch"><h1>{{sum}}</h1><button @click="changeSum">加一</button></div>
</template><script lang="ts"  setup name="watch">
import{ref,watch} from 'vue'let sum = ref(0)
function changeSum(){sum.value+=1
}
//直接监视watch(sum,(newValue,oldValue)=>{console.log('变化了')
})
//有返回值,返回值是一个结束监视函数const stopWatch = watch(sum ,(newValue,oldValue)=>{if(sum.value>10){stopWatch()}
})</script>

情况2: 监视ref定义的对象类型数据

默认当对象的某一个属性变化时,不会触发监视函数回调,只有当整个对象变化(地址值变化)才会响应,但是可以开启深度监视

  /* 监视,情况一:监视【ref】定义的【对象类型】数据,监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视watch的第一个参数是:被监视的数据watch的第二个参数是:监视的回调watch的第三个参数是:配置对象(deep、immediate等等.....) */watch(person,(newValue,oldValue)=>{console.log('person变化了',newValue,oldValue)},{deep:true})

情况3:监视reactive定义的对象类型数据

        和情况2类似,但是默认开启深度监视

情况4:监视ref和reactive定义的对象类型中的某个属性

1.若该属性不是对象类型,需要写成函数形式

2.是对象类型,可以直接写

 // 监视,情况四:监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式watch(()=> person.name,(newValue,oldValue)=>{console.log('person.name变化了',newValue,oldValue)}) // 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数watch(()=>person.car,(newValue,oldValue)=>{console.log('person.car变化了',newValue,oldValue)},{deep:true})

情况5:监视多个属性

// 监视,情况五:监视上述的多个数据watch([()=>person.name,person.car],(newValue,oldValue)=>{console.log('person.car变化了',newValue,oldValue)},{deep:true})

3.10. 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()}})

3.11.标签的ref属性

不同组件的即使有相同的ref也不会冲突

定位到组件上,如果想要取消保护机制,暴露属性可以用defineExpose

<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">import {ref,defineExpose} from 'vue'// 数据let name = ref('张三')let age = ref(18)/****************************//****************************/// 使用defineExpose将组件中的数据交给外部defineExpose({name,age})
</script>

补充:接口定义和使用

定义

// 定义一个接口,限制每个Person对象的格式
export interface PersonInter {id:string,name:string,age:number}// 定义一个自定义类型Persons
export type Persons = Array<PersonInter>

 使用

 import {type PersonInter} from './types'import {type Persons} from './types'let person:PersonInter = {id:'asyud7asfd01',name:张三',age:60}let personList:Array<PersonInter> = [{id:'asyud7asfd01',name:'张三',age:60},{id:'asyud7asfd02',name:"李四',age:18},{id: asyud7asfd03',name:'王五',age:5}]let persons = reactive<Persons>([{id:'e98219e12',name:'张三',age:18},{id:'e98219e13',name:'李四',age:19},{id:'e98219e14',name:'王五',age:20}])

3.12. props

让父组件能够向子组件传递数据。

<h2 a="1+1" :b="1+1" c="x"  :d="x"  ref="qwe"></h2>

<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} from 'vue'
import {type PersonInter} from '@/types'// 第一种写法:仅接收const props = defineProps(['list'])// 第二种写法:接收+限制类型const props = defineProps<{list:Persons}>()// 第三种写法:接收+限制类型+指定默认值+限制必要性let props = withDefaults(defineProps<{list?:Persons}>(),{list:()=>[{id:'asdasg01',name:'小猪佩奇',age:18}]})console.log(props)</script>

3.12.生命周期 

注意:使用时候需要从vue中impoort

创建阶段:setup

挂载阶段:onBeforeMountonMounted

更新阶段:onBeforeUpdateonUpdated

卸载阶段:onBeforeUnmountonUnmounted

3.13.自定义hook

 可以在src下创建hooks文件夹存放hook文件,命名一般为“useXxx",把具有联系的值和函数存放到一个文件夹

         例如

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}
}	

 useDog.ts

import {reactive,onMounted} from 'vue'
import axios,{AxiosError} from 'axios'export default function(){let dogList = reactive<string[]>([])// 方法async function getDog(){try {// 发请求let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')// 维护数据dogList.push(data.message)} catch (error) {// 处理错误const err = <AxiosError>errorconsole.log(err.message)}}// 挂载钩子onMounted(()=>{getDog()})//向外部暴露数据return {dogList,getDog}
}

具体使用

<template><h2>当前求和为:{{sum}}</h2><button @click="increment">点我+1</button><button @click="decrement">点我-1</button><hr><img v-for="(u,index) in dogList.urlList" :key="index" :src="(u as string)"> <span v-show="dogList.isLoading">加载中......</span><br><button @click="getDog">再来一只狗</button>
</template><script setup lang="ts">import useSum from './hooks/useSum'import useDog from './hooks/useDog'let {sum,increment,decrement} = useSum()let {dogList,getDog} = useDog()
</script>

4.路由 

4.1.配置

router文件下配置

import {createRouter,createWebHistory} from "vue-router"
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'const router = createRouter({history:createWebHistory(),routes:[{path:'/home'component:Home},{}
]
})

main.ts文件

import router from './router/index'
app.use(router)app.mount('#app')

App.vue文件

注意<RouterLink to=' '></RouterLink> 和<RouterView><RouterView>

  1. 路由组件通常存放在pages 或 views文件夹,一般组件通常存放在components文件夹。

  2. 通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载

<template><div class="app"><h2 class="title">Vue路由测试</h2><!-- 导航区 --><div class="navigate"><RouterLink to="/home" active-class="active">首页</RouterLink><RouterLink to="/news" active-class="active">新闻</RouterLink><RouterLink to="/about" 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>

4.2.路由器工作模式

history模式

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

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

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

hash模式

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

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

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

4.3.to的两种写法 

<RouterLink to="/home">主页</RouterLink>
<RouterLink to="{path:'/home'}">主页</RouterLink>

4.4.命名路由

在路由表中添加name属性

可以通过<RouterLink to="{name:'zhuye'}"><RouterLink>直接跳转 

 4.5.嵌套路由(子路由)

在一个路由下面增加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

4.6.路由传参

query参数

  1. 传递参数

    <!-- 跳转并携带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>
    
  2. 接收参数:

    import{useRoute} from 'vue-router'
    const route = useRoute()
    console.log(route.query)

params参数

  1. 传递参数

    <!-- 跳转并携带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>
    
  2. 接收参数:

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

3.占位

[name:'xinwen',path:'/news',component:News,children:[name:'xiang',//占位!!!!path: 'detail/:id/:title/:content',component:Detail[]

注意

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

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

4.7. 路由的prop配置

使传参更优雅

{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}
}

 4.8.replace属性

控制路由跳转时操作浏览器历史记录模式

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

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

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

 4.9.编程式导航

在vue3中,$route和$router变成了两个hook,就是在导航区以外的地方通过一些操作实现路由跳转

<template><div>当前路由路径: {{ route.path }}</div>
</template><script setup>
import { useRoute } from 'vue-router';const route = useRoute();
</script>
<template><button @click="goToHome">前往首页</button>
</template><script setup>
import { useRouter } from 'vue-router';const router = useRouter();const goToHome = () => {router.push('/home');
};
</script>

补充知识点,定时任务 

//挂载后,页面三秒自动跳转
onMounted(()=>{
router.push('/home')
},3000)

 4.10.重定向

将特定的路径,重新定向到已经有的路由,通过redirect

[path:'/',redirect:'/about'
]

5.pinia

5.1.搭建环境

step1:npm install pinia

step2:操作 src/main.ts

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')

 5.2.存储+读取数据

store是pinia的一个功能部件,我的理解是可以提取公共的数据或者函数供其他组件使用

在src/store中创建文件

具体编码src/store/count.ts

//引入defineStore用于创建store
import {defineStore} from 'pinia'//定义并暴露一个store
export const useCountstore = defineStore('count',{//动作actions:{},//状态state(){return {sum:6}},//计算getters:{}
})

使用 

<template><h1>当前的求和为:{{countStore.sum}}</h1>
</template>
<script setup lang="ts" name="count">
//引入对应的useXxxStore
import {useCountStore} from '@/src/store/count'
//调用对应的useXxxStore得到对应的store
const countStore = useCountStore()
</script>

5.3.修改数据

1.直接在调用的地方加(vue3特性)

countStore.sum = 666

2.批量修改,通过patch函数

countStore.$patch({

sum:999

age:111        

})

3.通过store里面的action创建修改store数据的方法

import {defineStore} from 'pinia'export const useCountStore = defineStore('count' ,{actions: {//加increment(value:number) {if (this.sum < 10) {//操作countStore中的sumthis.sum += value}},//减decrement(value:number){if(this.sum > 1){this.sum -= value}}},/*************/
})

 5.4.storeToRefs

借助storeToRefs会将store中的数据转化为ref对象,而store中的函数不变

通过toRefs会将store的所有都转化为ref对象,包括函数

<template><div class="count"><h2>当前求和为:{{sum}}</h2></div>
</template><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>

5.5.getters

state中的数据,需要经过处理后再使用时,可以使用getters配置。{感觉有点鸡肋,在state不是也可以吗},,记得在使用时和state一起import

// 引入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()}}
})

5.6.$subscribe

监视变化,和watch类似

mutate:关于状态变化的信息

state:最新的state对象

talkStore.$subscribe((mutate,state)=>{console.log('LoveTalk',mutate,state)
})

 5.7.store组合式写法

将数据和方法写在一个函数里面,别忘了最后需要return交出去

import {defineStore} from 'pinia'
import { ref } from 'vue';export const useSumStore = defineStore('sum' ,()=>{const sum = ref(999)function add(){sum.value++
}return {sum,add}
})

6.组件通信

6.1.props

父传子,引入子组件的时候直接附带需要传递的值

父传子

<template><div class="father"><h3>父组件,</h3><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('奔驰')
</script>

子接受,通过defineProps

defineProps(['car'])

 

 子传父,需要通过父传递的函数把值传递给父,就像父定义了一个构造函数,但是由子来调用这个构造函数从而获取具体的值

子调用父的函数

<template><div class="child"><h3>子组件</h3><h4>我的玩具:{{ toy }}</h4><button @click="getToy(toy)">玩具给父亲</button></div>
</template><script setup lang="ts" name="Child">import { ref } from "vue";const toy = ref('奥特曼')defineProps(['getToy'])
</script>

父通过子调用函数获取值

<template><div class="father"><h3>父组件,</h3><h4>儿子给的玩具:{{ toy }}</h4><Child :getToy="getToy"/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";// 数据const toy = ref()// 方法function getToy(value:string){toy.value = value}
</script>

6.2 自定义事件

我认为这又有点像一种高级的监听机制,父组件在子组件绑定一个事件并声明一个回调函数,只要子组件发生这个事件,父组件就会调用这个回调函数,并且还会受到子组件的值

主要是注意一些格式,子组件在接受事件的时候 通过const emits = defineEmits(['send-toy']) 

使用时通过emit('send-toy' ,toy)来响应事件,从而时父组件接受事件附带的值并执行回调函数

 

6.3mitt

        好像一个第三方的自定义事件功能,接收数据者定义事件,提供数据者触发事件,相比自定义事件,更“自由灵活”

step1:npm i mitt

step2:在util文件夹中创建emitter.ts

//引入emit
import mitt from "mitt"//创建emitter
const emitter = mitt()//创建并暴露mitt
export default emitter

 绑定事件

emitter.on('send-toy' (value)=>{ console.log("接受value并执行回调函数")})

触发事件

emitter.emit('send-toy' ,666)

注意,在组件卸载时候,尽量解绑当前组件绑定的事件,避免消耗内存

onUmMounted(()=>{  emitter.off('send-toy')})

6.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"
>

 

6.5.$attrs

通常用于父与孙的传递,但是中间的桥梁是子组件,

具体说明:$attrs是一个对象,包含所有父组件传入的标签属性。(个人理解:动态的资源集合)

注意:$attrs会排除props中已经声明的属性(相当于已经被用了),但把剩下的仍在$attrs中

父组件

<template><div class="father"><h3>父组件</h3><Child :a="a" :b="b" :c="c" :d="d" 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)let c = ref(3)let d = ref(4)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>c:{{ c }}</h4><h4>d:{{ d }}</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>

6.6.$refs,$parent

  1. 概述:

    • $refs用于 :父→子。
    • $parent用于:子→父。
  2. 原理如下:

    属性说明
    $refs值为对象,包含所有被ref属性标识的DOM元素或组件实例。
    $parent值为对象,当前组件的父组件实例对象。

但是需要用 defineExpose暴露出去,使用时候不需要显式传递,直接用

6.7. provide和inject

  • 在祖先组件中通过provide配置向后代组件提供数据
  • 在后代组件中通过inject配置来声明接收数据

在父组件中,通过provide提供数据

<template><div class="father"><h3>父组件</h3><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>

后代中通过inject接受数据,尽量代码有默认值

<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')

 

 6.7.solt

1.默认插槽

父组件在声明子组件时会传递一些供以显示的数据,这时候用插槽为这些数据的显示提供位置

父组件中:<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>

2.具名插槽

指定插在哪个位置,通过v-slot或者#slot

父组件中:<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>

3.作用域插槽

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

子组件通过在插槽声明的位置声明数据,由使用者操作

父组件中:<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>

7.其他API

7.1.shallowRef 与 shallowReactive 

绕开深度响应,提升性能

shallowRef

  1. 作用:创建一个响应式数据,但只对顶层【属性】进行响应式处理。

  2. 用法:

    let myVar = shallowRef(initialValue);
    
  3. 特点:只跟踪引用值的变化,不关心值内部的属性变化。

shallowReactive

  1. 作用:创建一个浅层响应式对象,只会使对象的【最顶层属性】变成响应式的,对象内部的嵌套属性则不会变成响应式的

  2. 用法:

    const myObj = shallowReactive({ ... });
  3. 特点:对象的顶层属性是响应式的,但嵌套对象的属性不是。

 

7.2.readonly 与 shallowReadonly

readonly

  1. 作用:用于创建一个对象的深只读副本。

  2. 用法:

    const original = reactive({ ... });
    const readOnlyCopy = readonly(original);
    
  3. 特点:

    • 对象的所有嵌套属性都将变为只读。
    • 任何尝试修改这个对象的操作都会被阻止(在开发模式下,还会在控制台中发出警告)。
  4. 应用场景:

    • 创建不可变的状态快照。
    • 保护全局状态或配置不被修改。

shallowReadonly

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

  2. 用法:

    const original = reactive({ ... });
    const shallowReadOnlyCopy = shallowReadonly(original);
    
  3. 特点:

    • 只将对象的顶层属性设置为只读,对象内部的嵌套属性仍然是可变的。

    • 适用于只需保护对象顶层属性的场景。

7.3. toRaw 与 markRaw

toRaw

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

markRaw

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

import { reactive,toRaw,markRaw,isReactive } from "vue";/* toRaw */
// 响应式对象
let person = reactive({name:'tony',age:18})
// 原始对象
let rawPerson = toRaw(person)/* markRaw */
let citysd = markRaw([{id:'asdda01',name:'北京'},{id:'asdda02',name:'上海'},{id:'asdda03',name:'天津'},{id:'asdda04',name:'重庆'}
])

7.4.customRef

自定义的ref,可以实现特殊的逻辑,一般把自定义的ref封装为一个hook

import {customRef } from "vue";export default function(initValue:string,delay:number){let msg = customRef((track,trigger)=>{let timer:numberreturn {get(){track() // 告诉Vue数据msg很重要,要对msg持续关注,一旦变化就更新return initValue},set(value){clearTimeout(timer)timer = setTimeout(() => {initValue = valuetrigger() //通知Vue数据msg变化了}, delay);}}}) return {msg}
}

8.Vue3新组件 

8.1.Teleport

将窗口移动到指定位置

<teleport to='body' ><div class="modal" v-show="isShow"><h2>我是一个弹窗</h2><p>我是弹窗中的一些内容</p><button @click="isShow = false">关闭弹窗</button></div>
</teleport>

 

8.2.Suspense

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • <template><div class="app"><h3>我是App组件</h3><Suspense>//异步组件加载完成后显示内容<template v-slot:default><Child/></template>//异步组件加载过程中显示内容,加载之后消失<template v-slot:fallback><h3>加载中.......</h3></template></Suspense></div>
    </template>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/28402.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【五.LangChain技术与应用】【8.LangChain提示词模板基础:从入门到精通】

早上八点,你端着咖啡打开IDE,老板刚甩来需求:“做个能自动生成产品描述的AI工具”。你自信满满地打开ChatGPT的API文档,结果半小时后对着满屏的"输出结果不稳定"、"格式总出错"抓耳挠腮——这时候你真需要好好认识下LangChain里的提示词模板了。 一、…

基于编程语言的建筑行业施工图设计系统开发可行性研究————从参数化建模到全流程自动化的技术路径分析

基于编程语言的建筑行业施工图设计系统开发可行性研究————从参数化建模到全流程自动化的技术路径分析 文章目录 **基于编程语言的建筑行业施工图设计系统开发可行性研究————从参数化建模到全流程自动化的技术路径分析** 摘要引言一、技术可行性深度剖析1.1 现有编程语言…

【Linux文件操作篇】IO基础——被打开的文件,引入文件描述符

--------------------------------------------------------------------------------------------------------------------------------- 每日鸡汤&#xff1a;现实会告诉你&#xff0c;不努力就会被生活给踩死。无需找什么借口&#xff0c;一无所有&#xff0c;就是拼的理由…

Docker 学习(三)——数据管理、端口映射、容器互联

一、数据管理 容器中的管理数据主要有两种方式&#xff1a; 数据卷 &#xff08;Data Volumes&#xff09;&#xff1a; 容器内数据直接映射到本地主机环境&#xff1b; 数据 卷容器&#xff08; Data Volume Containers&#xff09;&#xff1a; 使用特定容器维护数据卷 1.…

3月5日作业

代码作业&#xff1a; #!/bin/bash# 清空目录函数 safe_clear_dir() {local dir"$1"local name"$2"if [ -d "$dir" ]; thenwhile true; doread -p "检测到 $name 目录已存在&#xff0c;请选择操作&#xff1a; 1) 清空目录内容 2) 保留目…

通义万相2.1:开启视频生成新时代

文章摘要&#xff1a;通义万相 2.1 是一款在人工智能视频生成领域具有里程碑意义的工具&#xff0c;它通过核心技术的升级和创新&#xff0c;为创作者提供了更强大、更智能的创作能力。本文详细介绍了通义万相 2.1 的背景、核心技术、功能特性、性能评测、用户反馈以及应用场景…

GPU/CUDA 发展编年史:从 3D 渲染到 AI 大模型时代(上)

目录 文章目录 目录1960s~1999&#xff1a;GPU 的诞生&#xff1a;光栅化&#xff08;Rasterization&#xff09;3D 渲染算法的硬件化实现之路学术界算法研究历程工业界产品研发历程光栅化技术原理光栅化技术的软件实现&#xff1a;OpenGL 3D 渲染管线设计1. 顶点处理&#xff…

如何直接导出某个conda环境中的包, 然后直接用 pip install -r requirements.txt 在新环境中安装

1. 导出 Conda 环境配置 conda list --export > conda_requirements.txt这将生成一个 conda_requirements.txt 文件&#xff0c;其中包含当前环境中所有包的列表及其版本信息。 2. 转换为 requirements.txt 文件 grep -v "^#" conda_requirements.txt | cut -d …

【我的 PWN 学习手札】House of Emma

House of Emma 参考文献 第七届“湖湘杯” House _OF _Emma | 设计思路与解析-安全KER - 安全资讯平台 文章 - house of emma 心得体会 - 先知社区 前一篇博客【我的 PWN 学习手札】House of Kiwi-CSDN博客的利用手法有两个关键点&#xff0c;其一是利用__malloc_assert进入…

沃尔玛跨境电商自养号技术指南,助力销量腾飞

在跨境电商领域&#xff0c;沃尔玛平台为卖家提供了广阔的市场空间。对于技术型卖家而言&#xff0c;利用自养号技术提升产品销量是一项极具潜力的策略。本文将深入探讨沃尔玛自养号技术&#xff0c;从原理到实践&#xff0c;为你提供全面的技术指南。 自养号技术原理与架构 自…

Redis|集群 Cluster

文章目录 是什么能干嘛集群算法-分片-槽位slotredis集群的槽位slotredis集群的分片分片槽位的优势slot槽位映射——业界的3种解决方案小厂&#xff1a;哈希取余分区中厂&#xff1a;一致性哈希算法分区大厂&#xff1a;哈希槽分区 面试题&#xff1a;为什么 Redis 集群的最大槽…

DeepSeek R1助力,腾讯AI代码助手解锁音乐创作新

目录 1. DeepSeekR1模型简介2. 歌词创作流程2.1 准备工作2.2 歌词生成技巧 3. 音乐制作环节3.1 主流AI音乐生成平台 4. 歌曲欣赏5. 总结展望 1. DeepSeekR1模型简介 腾讯AI代码助手最新推出的DeepSeekR1模型不仅在代码生成方面表现出色&#xff0c;其强大的自然语言处理能力也…

学习threejs,使用LineBasicMaterial基础线材质

&#x1f468;‍⚕️ 主页&#xff1a; gis分享者 &#x1f468;‍⚕️ 感谢各位大佬 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍⚕️ 收录于专栏&#xff1a;threejs gis工程师 文章目录 一、&#x1f340;前言1.1 ☘️THREE.LineBasicMaterial1.…

Spring Boot 整合 JMS-ActiveMQ,并安装 ActiveMQ

1. 安装 ActiveMQ 1.1 下载 ActiveMQ 访问 ActiveMQ 官方下载页面&#xff0c;根据你的操作系统选择合适的版本进行下载。这里以 Linux 系统&#xff0c;Java环境1.8版本为例&#xff0c;下载 apache-activemq-5.16.7-bin.tar.gz。 1.2 解压文件 将下载的压缩包解压到指定目…

C语言学习笔记-初阶(28)操作符详解2

1. 逗号操作符、逗号表达式 exp1, exp2, exp3, …expN 逗号表达式&#xff0c;就是用逗号隔开的多个表达式。 逗号表达式&#xff0c;从左向右依次执行。整个表达式的结果是最后一个表达式的结果。 //代码1 int a 1; int b 2; int c (a>b, ab10, a, ba1);//逗号表达…

《机器学习数学基础》补充资料:连续正态分布随机变量的熵

《机器学习数学基础》第 416 页给出了连续型随机变量的熵的定义&#xff0c;并且在第 417 页以正态分布为例&#xff0c;给出了符合 N ( 0 , σ 2 ) N(0,\sigma^2) N(0,σ2) 的随机变量的熵。 注意&#xff1a;在第 4 次印刷以及之前的版本中&#xff0c;此处有误&#xff0c…

ReconDreamer:通过在线恢复构建驾驶场景重建的世界模型

24年11月来自极佳科技、北大、理想汽车和中科院自动化所的论文“ReconDreamer: Crafting World Models for Driving Scene Reconstruction via Online Restoration”。 ReconDreamer&#xff0c;通过逐步整合世界模型知识来增强驾驶场景重建。具体来说&#xff0c;DriveRestor…

写一个python程序,找出1000以内的质数

这是一道常考的题&#xff0c;大家一定得学会。 解题思路&#xff1a; 需要理解质数的定义。质数是大于1的自然数&#xff0c;除了1和它本身外没有其他因数。所以&#xff0c;我需要生成2到1000之间的所有数&#xff0c;然后检查每个数是否是质数。 def find_primes(n):&quo…

软考-数据库开发工程师-3.1-数据结构-线性结构

第3章内容比较多&#xff0c;内容考试分数占比较大&#xff0c;6分左右 线性表 1、线性表的定义 一个线性表是n个元素的有限序列(n≥0)&#xff0c;通常表示为(a1&#xff0c;a2, a3,…an). 2、线性表的顺序存储(顺序表) 是指用一组地址连续的存储单元依次存储线性表中的数据元…

【技术点】RAG

本文非自己原创&#xff0c;只是学习过程中资料的总结合并。具体来自于以下链接 https://cloud.google.com/use-cases/retrieval-augmented-generation 一文读懂&#xff1a;大模型RAG&#xff08;检索增强生成&#xff09;含高级方法 RAG基础 定义 RAG&#xff08;检索增…