Vue3.0尚硅谷(讲师:张天禹)视频学习笔记

一、创建Vue3.0工程

1、使用vue-cli创建

官方文档:​https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create​

## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version    / vue -V
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve

2、使用vite创建

官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite

vite官网:https://vitejs.cn

(1)什么是vite?

         新一代前端构建工具(webpack)

(2)优势如下:

         ① 开发环境中,无需打包操作,可快速的冷启动。

         ② 轻量快速的热重载(HMR)。

         ③ 真正的按需编译,不再等待整个应用编译完成。

## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install 
##  运行
npm run dev

二、分析工程结构

(1)脚手架安装失败的原因

① npm原因:建议清理缓存

② 重装node.js

③ 网络问题:配置淘宝镜像

 (2)Vue2.0和Vue3.0的区别

(3)查看Vue3.0里creatApp里的东西

 (4)关闭语法检查

  • vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  //关闭语法检查
  lintOnSave:false
})

(5)Vue3.0的特殊之处

① Vue3组件的模板结构中可以没有根标签div

<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

② main.js

// createApp:引入的不在是Vue的构造函数,引入的是一个名为createApp的工厂函数(无需new,里面的方法直接调用,首字母小写)
import { createApp } from 'vue'
import App from './App.vue'

// 创建应用实例对象--app(类似于之前vue2中的vm,但app比vm"轻",因为去掉了一些不用的函数)
const app=createApp(App)
// 查看app里面的内容 
console.log('@@@@',app)
// 挂载
app.mount('#app')

// 1秒后卸载 app
setTimeout(()=>{  
    app.unmount('#app')
},1000)


// Vue2:
// const vm=new VueElement({
//     render:h=>h(App)
// })
// vm.$mount('#app')

三、常用Composition API(组合式API)

官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite

1、拉开序幕的setup

(1)理解:Vue3.0中一个新的配置项,值为一个函数。

(2)setup是所有Compositon API(组合API) “表演的舞台”

(3)组件中所用到的:数据、方法等等,均要配置在setup中。

(4)setup函数的两种返回值:

   ① 若返回一个对象,则对象中的属性、方法,在模板中均可以直接使用(重点关注!  )

   ② 若返回一个渲染函数:则可以自定义渲染内容。(了解)

(5)注意点:

    ① 尽量不要与Vue2.x配置混用 

  • Vue2.x配置(data、methos、computed...)中可以访问到setup中的属性、方法。

  • 但在setup中不能访问到Vue2.x配置(data、methods、computed...)。

  • 如有重名,setup优先。

  ② setup不能是一个async函数,因为返回值不再是return的对象,而是promise, 模板看不到 return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)

(6)代码展示

  • App.vue
<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <h1>一个人的信息</h1>
  <h2>姓名:{{name}}</h2>
  <h2>年龄:{{age}}</h2>
  <!-- 如有重名,setup优先,a为200 -->
  <h2>a的值是:{{a}}</h2>    
  <button @click="sayHello">说话</button><br/><br/>
  <button @click="sayWelcome">说话(Vue2所配置的—sayWelcome)</button><br/><br/>
  <button @click="test1">测试一下在Vue2的配置中去读取Vue3中的数据、方法</button><br/><br/>
  <button @click="test2">测试一下在Vue3的setup配置中去读取Vue2中的数据、方法</button>
</template>

<script>

// import {h} from 'vue'
export default {
  name: 'App',
  data(){
    return {
      sex:'男',
      a:100
    }
  },
  methods:{
    sayWelcome(){
      alert('晚安~各位')
    },
    test1(){
      console.log(this.sex);
      console.log(this.name);
      console.log(this.age);
      this.sayHello()
    },
    
  },
  //此处只是测试一下setup,暂时不考虑响应式的问题
  setup() {
    //数据
    let name = '玛卡巴卡'
    let age = '18'
    let a = 200
    //方法
    function sayHello(){
      alert(`我叫${name},我今年${age}岁了`)
    }

    function test2(){
      console.log(name);
      console.log(age);
      console.log(sayHello);
      console.log(this.sex);          //undefined
      console.log(this.sayWelcome);   //undefined
    }

    //返回一个对象(常用)
    return {
      name,
      age,
      sayHello,
      test2,
      a
    }

    //h是createElement函数的缩写
    //返回一个渲染函数
    // return()=>h('h1','xixi')
  }

}
</script>

<style>

</style>

 

  
2、ref函数

(1)作用:定义一个响应式的数据

(2)语法:const xxx = ref(initValue)

  • 创建一个包含响应式数据的引用对象的引用对象(reference对象,简称ref对象)
  • JS中操作数据:xxx.value
  • 模板中读取数据:不需要.value,直接<div>{{xxx}}</div>

(3)备注:

  • 接受的数据可以是:基本类型、也可以是对象类型。
  • 基本类型的数据:响应式依然是靠Object.defineProperty()的get与set完成的。
  • 对象类型的数据:内部“求助”了Vue3.0中的一个新函数——reactive函数。

(4)代码展示

  • App.vue
<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <h1>一个人的信息</h1>
  <h2>姓名:{{name}}</h2>
  <h2>年龄:{{age}}</h2>
  <h2>工作种类:{{job.type}}</h2>
  <h2>工作薪水:{{job.salary}}</h2>
  <button @click="changeInfo">修改人的信息</button>
</template>

<script>

// import {h} from 'vue'
import {ref} from 'vue'
export default {
  name: 'App',
  setup() {
    //数据
    let name = ref('玛卡巴卡')
    let age = ref(18)
    let job = ref({
      type:'前端工程师',
      salary:'30k'
    })
    
    //方法
    function changeInfo(){
      name.value = '李四',
      age.value = 20
      job.value.type = '土建工程师'
      job.value.salary = '20k'
      console.log(name,age,job);
    }
    //返回一个对象(常用)
    return {
      name,
      age,
      job,
      changeInfo
    }

    //h是createElement函数的缩写
    //返回一个渲染函数
    // return()=>h('h1','xixi')
  }

}
</script>

<style>

</style>

3、reactive函数

(1)作用:定义一个对象类型的响应式数据(基本类型不要用它,用ref函数)

(2)语法:

        const 代理对象 = reactive(源对象)接收一个对象(或数组),返回一个代理对象

        (Proxy的实例对象,简称proxy对象)

(3)reactive定义的响应式数据是深层次的。

(4)内部基于ES6的Proxy实现,通过代理对象操作源对象内部数据进行操作。

Proxy

作用:遵循响应式原理,用来相应数据

只有reactive才能把对象数据变为proxy

ref偷偷求助了reactive

(5)代码展示

  • App.vue
<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <h1>一个人的信息</h1>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h2>工作种类:{{person.job.type}}</h2>
  <h2>工作薪水:{{person.job.salary}}</h2>
  <h2>爱好:{{person.hobby}}</h2>
  <h2>测试的数据c:{{person.job.a.b.c}}</h2>
  <button @click="changeInfo">修改人的信息</button>
</template>

<script>

// import {h} from 'vue'
import { ref, reactive } from 'vue'
export default {
  name: 'App',
  setup() {
    //数据
    // let name = ref('玛卡巴卡')
    // let age = ref(18)
    // let job = reactive({
    //   type:'前端工程师',
    //   salary:'30k',
    //   // reactive定义的响应式数据是“深层次的”
    //   a:{
    //     b:{
    //       c:666
    //     }
    //   }
    // })
    // let hobby = reactive(['抽烟','喝酒','烫头'])
    let person = reactive({
      name: '玛卡巴卡',
      age: 18,
      job: {
        type: '前端工程师',
        salary: '30k',
        a: {
          b: {
            c: 666
          }
        }

      },
      hobby: ['抽烟', '喝酒', '烫头']
    })


    //方法
    function changeInfo() {
      person.name = '李四',
      person.age = 20
      console.log(person.job);
      person.job.type = '土建工程师'
      person.job.salary = '20k',
      person.job.a.b.c = 999
      person.hobby[0] = '学习'

    }
    //返回一个对象(常用)
    return {
      person,
      changeInfo
    }

    //h是createElement函数的缩写
    //返回一个渲染函数
    // return()=>h('h1','xixi')
  }

}
</script>

<style>

</style>

4、Vue3.0中的响应式原理

4.1 Vue2.x的响应式

(1)实现原理

① 对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)。

② 数组类型:通过重写更新数组的一系列方法来实现拦截,(对数组的变更方法进行了包裹)。

Object.defineProperty(data,'count',{
     get() {} ,
     set() {} ,
 })

③ 存在问题:

    新增属性、删除属性,界面不会更新。

   直接通过下标修改数组,界面不会自动更新。

4.2 Vue3.0的响应式

(1)实现原理

① 通过Proxy(代理):拦截对象中任意属性的变化,包括:属性值的书写、属性的添加、属性的删除等。

② 通过Reflect(反射):对源对象的属性进行操作。

③ MDN文档中描述Proxy与Reflect:

 Proxy:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Reflect:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect

new Proxy(data, {
	// 拦截读取属性值
    get (target, prop) {
    	return Reflect.get(target, prop)
    },
    // 拦截设置属性值或添加新属性
    set (target, prop, value) {
    	return Reflect.set(target, prop, value)
    },
    // 拦截删除属性
    deleteProperty (target, prop) {
    	return Reflect.deleteProperty(target, prop)
    }
})

proxy.name = 'tom'   

5、reactive对比ref

(1)从定义数据角度对比:

  • ref用来定义:基本类型数据
  • reactive用来定义:对象(或数组)类型数据
  • 备注:ref也可以用来定义对象(或数组)类型数据,它内部会自动通过reactive转为代理对象

(2)从原理角度对比:

  • ref通过Object.defineProperty()的get与set来实现响应式(数据劫持)。
  • reactive通过使用Proxy来实现响应式(数据劫持),并通过Reflect操作源对象内部的数据。

(3)从使用角度对比:

  • ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value。
  • reactive定义都数:操作数据与读取数据,均不需要.value。

6、setup的两个注意点

(1)setup执行的时机

在beforCreate之前执行一次,this是undefined。

(2)setup的参数

① props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。

② context:上下文对象

  • attrs:值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于this.$attrs。
  • slots:收到的插槽内容,相当于this.$slots。
  • emit:分发自定义事件都函数,相当于this.$emit。

7、计算属性与监视

7.1 computed函数

与Vue2.x中computed配置功能一致

(1)写法:

import {computed} from 'vue'

setup(){
    ...
	//计算属性——简写
    let fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
    })
    //计算属性——完整
    let fullName = computed({
        get(){
            return person.firstName + '-' + person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
}

(2)代码展示

  • src/components/Demo.vue
<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <h1>一个人的信息</h1>
  性:<input type="text" v-model="person.firstName">
  <br>
  名:<input type="text" v-model="person.lastName">
  <br>
  <span>全名:{{person.fullName}}</span>
  <br>
  全名:<input type="text" v-model="person.fullName">
</template>

<script>
import {reactive,computed} from 'vue'
export default {
  name: 'Demo',
  //Vue2的写法
  // computed:{
  //   fullName(){
  //     return this.person.firstName + '-' +this.person.lastName
  //   }
  // },

  setup() {
    //数据
    let person = reactive({
      firstName: '张',
      lastName: '三',
    })

    //计算属性(简写)——没有考虑计算属性被修改的情况
    // person.fullName = computed(()=>{
    //   return person.firstName + '-' + person.lastName
    // })

    //计算属性(完整写法)——考虑读和写
    person.fullName = computed({
      get(){
        return person.firstName + '-' + person.lastName
      },
      set(value){
         const nameArr = value.split('-')
         person.firstName = nameArr[0]
         person.lastName = nameArr[1]
      }
    })
    
    //返回一个对象(常用)
    return {
      person,

    }
  }
}
</script>

7.2 watch函数

与Vue2.x中watch配置功能一致

(1)两个“小坑”

  • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。
  • 监视reactive定义都响应式数据中都某个属性时:deep配置有效。
//情况一:监视ref定义的响应式数据
watch(sum,(newValue,oldValue)=>{
	console.log('sum变化了',newValue,oldValue)
},{immediate:true})

//情况二:监视多个ref定义的响应式数据
watch([sum,msg],(newValue,oldValue)=>{
	console.log('sum或msg变化了',newValue,oldValue)
}) 

/* 情况三:监视reactive定义的响应式数据
			若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
			若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 
*/
watch(person,(newValue,oldValue)=>{
	console.log('person变化了',newValue,oldValue)
},{immediate:true,deep:false}) //此处的deep配置不再奏效

//情况四:监视reactive定义的响应式数据中的某个属性
watch(()=>person.job,(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true}) 

//情况五:监视reactive定义的响应式数据中的某些属性
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true})

//特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效

(2)代码展示

src/components/Demo.vue

<template>
  <h2>当前求和为:{{ sum }}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>当前信息为:{{ msg }}</h2>
  <button @click="msg+='!'">修改信息</button>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h2>薪资:{{person.job.j1.salary}}k</h2>
  <button @click="person.name+='~'">修改姓名</button>
  <button @click="person.age++">增长年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>
</template>

<script>
import { ref,reactive,watch} from 'vue'
export default {
  name: 'Demo',
  watch: {
    // Vue2的写法
    // 写法二:
    // sum(newValue,oldValue) {
    //   console.log('sum的值变化了',oldValue,newValue)
    // }
    // 写法二:
    // sum: {
    //   immediate: true,  //立即执行
    //   deep: true,   //深度监听
    //   handler(newValue, oldValue) {
    //     console.log('sum的值变化了', oldValue, newValue)
    //   }
    // }
  },
  setup() {
    //数据
    let sum = ref(0)
    let msg = ref('你好啊')
    let person = reactive({
      name:'玛卡巴卡',
      age:18,
      job:{
        j1:{
          salary:0

        }
      }

    })

    //监视
    //情况一:监视ref定义都响应式数据
    // watch(sum,(newValue,oldValue)=>{
    //    console.log('sum变了',newValue,oldValue);
    // })

    //情况二:监视多个ref定义的响应式数据
    // watch([sum,msg],(newValue,oldValue)=>{
    //   console.log('sum或msg变了',newValue,oldValue);
    // })

    //情况三:监视reactive定义的响应式数据
      // 若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
			// 若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 (deep配置无效)
    // watch(person,(newValue,oldValue)=>{
    //   console.log('person变了',newValue,oldValue);
    // },{immediate:true,deep:false})

    
    //情况四:监视reactive定义的响应式数据中的某个属性
    // watch(()=>person.job,(newValue,oldValue)=>{
    //   console.log('person的job变化了',newValue,oldValue)
    // },{immediate:true,deep:true})

     //情况五:监视reactive定义的响应式数据中的某些属性
    //  watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
    //   console.log('person的job变化了',newValue,oldValue)
    // },{immediate:true,deep:true})

    //特殊情况
    watch(()=>person.job,(newValue,oldValue)=>{
      console.log('person的job变化了',newValue,oldValue)
    },{deep:true})  //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效

    //返回一个对象(常用)
    return {
      sum,
      msg,
      person
    }
  }
}
</script>

 7.3 watchEffect函数

① watch的套路是:既要指明监视的属性,也要指明监视的回调。

② watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。

③ watchEffect有点像computed:

  • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。

  • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。

//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
watchEffect(()=>{
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
})

8、生命周期

(1)Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有两个被更名:

  • beforeDestroy改名为beforUnmount
  • destroyed改名为unmounted

(2)Vue3.0也提供了Composition API形式的生命周期钩子,与Vue2.x中钩子对应关系如下:

  • beforeCreate ===> setup()
  • created ===> setup()
  • beforeMount ===> onBeforeMount
  • mounted ===> onMounted
  • beforeUpdate ===> onBeforeUpdate
  • updated ===> onUpdated
  • beforeUnmount ===> onBeforeUnmount
  • unmounted ===> onUnmouted

9、自定义hook函数

(1)什么是hook?

本质是一个函数,把setup函数中使用的Composition API进行了封装。

类似于Vue2.x中的mixin。

自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂。

(2)代码展示

  • src/App.vue
<template>
    <button @click="isShowDemo = !isShowDemo">切换隐藏/显示</button>
    <Demo v-if="isShowDemo"/>
    <hr>
    <Test/>
</template>

<script>
import {ref} from 'vue'
import Demo from './components/Demo.vue'
import Test from './components/Test.vue'
export default {
    name: "App",
    components: { Demo, Test },
    setup(){
        let isShowDemo = ref(true)
        return {isShowDemo}
    }
}
</script>

  • src/hooks/usePoint.js
import { reactive,onMounted,onBeforeUnmount } from 'vue'
export default function (){
    //实现鼠标“打点”相关的数据
    let point = reactive({
        x:0,
        y:0
      })
    //实现鼠标“打点”相关的方法
    function savePoint(event){
        point.x = event.pageX
        point.y = event.pageY
        console.log(event.pageX,event.pageY);
    }

    实现鼠标“打点”相关的生命周期钩子
    onMounted(()=>{
      window.addEventListener('click',savePoint)
    })

    onBeforeUnmount(() => {
      window.removeEventListener('click',savePoint)
    })

    return point
    
}

// export default savePoint
  • src/components/Demo.vue
<template>
  <h2>当前求和为:{{ sum }}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>

<script>
import { ref } from 'vue'
import usePoint from '../hooks/usePoint'
export default {
  name: 'Demo',
  setup() {
    //数据
    let sum = ref(0)
    let point = usePoint()

    //返回一个对象(常用)
     return {sum,point}
  },
  
}
</script>

  • src/components/Test.vue
<template>
  <h2>我是Test组件</h2>
  <h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>

<script>
import usePoint from '../hooks/usePoint'
export default {
    name:'Test',
    setup(){
        const point = usePoint()
        return {point}
    }
}
</script>

<style>

</style>

10、toRef

(1)作用

创建一个ref对象,其value值指向另一个对象中的某个属性。

(2)语法

const name = toRef(person,'name')

(3)应用

要将响应式对象中的某个属性单独提供给外部使用时。

(4)扩展

toRefs与toRef功能一致,但可以批量创建多个ref对象,语法:toRefs(person)

(5)代码展示

  • src/components/Demo.vue
<template>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{job.j1.salary}}k</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>

</template>

<script>
import {reactive,toRefs} from 'vue'
export default {
     name:'Demo',
     setup(){
      //数据
       let person = reactive({
          name:'张三',
          age:20,
          job:{
            j1:{
              salary:20
            }
          }
       })
       //返回一个对象
       return {
        person,
        // name:toRef(person,'name'),
        // age:toRef(person,'age'),
        // salary:toRef(person.job,'salary')
        ...toRefs(person)
       }
     }
    
}
</script>

<style>

</style>

三、其它Composition API

1、shallowReactive与shallowRef

shallowReactive:只处理对象最外层属性的响应式(浅响应式)。

shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理。

什么时候使用?

① 如有有一个数据,结构比较深, 但变化时只是外层属性变化 ===> shallowReactive。

② 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生成新的对象来替换 ===> shallowRef。

代码展示:

  • src/components/Demo.vue
<template>
<h4>当前的x值是:{{x.y}}</h4>
<button @click="x.y++">点我x+1</button>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{job.j1.salary}}k</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>

</template>

<script>
import {ref,reactive,toRefs,shallowReactive,shallowRef} from 'vue'
export default {
     name:'Demo',
     setup(){
      //数据
      //let person = shallowReactive({    只考虑第一层数据的响应式
       let person = shallowReactive({
          name:'张三',
          age:20,
          job:{
            j1:{
              salary:20
            }
          }
       })
      //  shallowRef不处理对象类型的响应式
       let x =ref({
        y:0
       })

       //返回一个对象
       return {
        x,
        person,
        // name:toRef(person,'name'),
        // age:toRef(person,'age'),
        // salary:toRef(person.job,'salary')
        ...toRefs(person)
       }
     }
    
}
</script>

<style>

</style>

2、readonly与shallowReadonly

readonly:让一个响应式数据变为只读的(深只读)。

shallowReadonly:让一个响应式数据变为只读的(浅只读)。

应用场景:不希望数据被修改时。

代码展示:

src/components/Demo.vue

<template>
<h4>当前求和为{{sum}}</h4>
<button @click="sum++">点我x+1</button>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{job.j1.salary}}k</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>

</template>

<script>
import {ref,reactive,toRefs,readonly,shallowReadonly} from 'vue'
export default {
     name:'Demo',
     setup(){
      //数据
      let sum = ref(0)
       let person = reactive({
          name:'张三',
          age:20,
          job:{
            j1:{
              salary:20
            }
          }
       })
      //  person = readonly(person)    数据都不可以改
       sum = readonly(sum)
       person = shallowReadonly(person)    //job里的salary可以修改

       //返回一个对象
       return {
        sum,
        ...toRefs(person)
       }
     }
    
}
</script>

<style>

</style>

3、toRaw与markRaw

3.1 toRaw

(1)作用:将一个由reactive生成的响应式对象转为普通对象

(2)使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面的更新。

3.2 markRaw

(1)作用:标记一个对象,使其永远不会再成为响应式对象。

(2)使用场景:

         ① 有些值不应被设置为响应式的,例如复杂的第三方类库等。

         ② 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能。

代码展示:

  • src/components/Demo.vue
<template>
<h4>当前求和为{{sum}}</h4>
<button @click="sum++">点我x+1</button>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{job.j1.salary}}k</h2>
<h2 v-show="person.car">座驾信息:{{person.car}}</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>
<button @click="showRawPerson">输出最原始的person</button><br>
<button @click="addCar">给人添加一台车</button>
<button @click="person.car.name+='!'">换车名</button>
<button @click="changePrice">换价格</button>

</template>

<script>
import {ref,reactive,toRefs,toRaw,markRaw} from 'vue'
export default {
     name:'Demo',
     setup(){
      //数据
      let sum = ref(0)
       let person = reactive({
          name:'张三',
          age:20,
          job:{
            j1:{
              salary:20
            }
          }
       })

       function showRawPerson(){
        //console.log(person);   输出的是加工完成的响应式对象
        const p = toRaw(person)
        console.log(p);
       }

       function addCar(){
        let car = {name:'奔驰',price:40}
        person.car = markRaw(car)
       }

       function changePrice(){
        person.car.price++
        console.log(person.car.price);
       }
     

       //返回一个对象
       return {
        sum,
        person,
        ...toRefs(person),
        showRawPerson,
        changePrice,
        addCar,
       }
     }
    
}
</script>

<style>

</style>

4、customRef(自定义ref)

(1)作用:

创建一个自定义的ref,并对其依赖项跟踪和更新触发进行显示控制。

(2)实现防抖效果:

<template>
	<input type="text" v-model="keyword">
	<h3>{{keyword}}</h3>
</template>

<script>
	import {ref,customRef} from 'vue'
	export default {
		name:'Demo',
		setup(){
			// let keyword = ref('hello') //使用Vue准备好的内置ref
			//自定义一个myRef
			function myRef(value,delay){
				let timer
				//通过customRef去实现自定义
				return customRef((track,trigger)=>{
					return{
						get(){
							track() //告诉Vue这个value值是需要被“追踪”的
							return value
						},
						set(newValue){
							clearTimeout(timer)
							timer = setTimeout(()=>{
								value = newValue
								trigger() //告诉Vue去更新界面
							},delay)
						}
					}
				})
			}
			let keyword = myRef('hello',500) //使用程序员自定义的ref
			return {
				keyword
			}
		}
	}
</script>

(3)代码展示

  • src/App.vue
<template>
   <input type="text" v-model="keyWord">
   <h3>{{keyWord}}</h3>
</template>

<script>
import {customRef} from 'vue'
export default {
    name: "App",
    setup(){
       //自定义一个ref,名为:myRef
       function myRef(value,delay){
          let timer
          return customRef((track,trigger)=>{
            return {
                get(){
                   console.log(`有人从myRef这个容器中读取数据了,我把${value}给他了`)   //input和h3各读取了一次
                   track()   //通知Vue追踪value的变化(提前和get商量一下,让他认为这个value是有用的)
                   return value
                },
                set(newValue){
                    console.log(`有人把myRef这个容器中的数据修改了:${newValue}给他了`)
                    clearTimeout(timer)    //函数防抖
                    timer = setTimeout(()=>{
                      value = newValue
                      trigger()        //通知vue去重新解析模板
                    },delay)
                    
                }
            }
          })
       } 
      //let keyWord = ref('hello')  //使用vue提供的内置ref
      let keyWord = myRef('hello',500)  //使用程序员自定义的ref
       return {keyWord}
    }
}
</script>

 

5、provide与inject

(1)作用

实现祖孙组件间通信

(2)套路

父组件有一个provide选项来提供数据,子组件有一个inject选项来开始使用这些数据 。

(3)具体写法:

① 祖组件中:

setup(){
	......
    let car = reactive({name:'奔驰',price:'40万'})
    provide('car',car)
    ......
}

② 后代组件中:

setup(props,context){
	......
    const car = inject('car')
    return {car}
	......
}

(4)代码展示

  • src/App.vue
<template>
  <div class="app">
   <h3>我是App组件(祖),{{name}}---{{price}}</h3>
   <Child/>
  </div>
</template>

<script>
import Child from './components/Child.vue'
import {reactive,toRefs,provide} from 'vue'
export default {
   name:'App',
   components:{Child},
   setup(){
      let car = reactive({
         name:'奔驰',
         price:'40W'
      })
      provide('car',car)
      return {...toRefs(car)}
   }
}
</script>

<style>
.app {
   background-color: gray;
   padding:10px
}
</style>
  • src/components/Child.vue
<template>
    <div class="child">
     <h3>我是Child组件(子)</h3>
     <Son/>
    </div>
  </template>
  
  <script>
 import Son from './Son.vue'
  export default {
     name:'Child',
     components:{Son}
  }
  </script>
  
  <style>
  .child {
     background-color: skyblue;
     padding:10px
  }
  </style>
  • src/components/Son.vue
<template>
    <div class="son">
     <h3>我是Son组件(孙),{{car.name}}---{{car.price}}</h3>
    </div>
  </template>
  
  <script>
  import {inject} from 'vue'
  export default {
     name:'Son',
     setup(){
      const car = inject('car')
      return {car}
     }
  }
  </script>
  
  <style>
  .son {
     background-color: orange;
     padding:10px
  }
  </style>

 6、响应式数据的判断

(1)isRef:检查一个值是否为一个 ref 对象 。

(2)isReactive:检查一个对象是否是由reactive创建的响应式代理。

(3)isReadonly:检查一个对象是否是由readonly创建的只读代理。

(4)isProxy:检查一个对象是否是由reactive或者readonly 方法创建的代理 。

四、Composition API的优势

1、Options API(配置式API)存在的问题

使用传统的OptionAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改。

 

 

2、Composition API的优势

我们可以更加优雅的组织我们的代码,函数。让相关功能的代码更加有序的组织在一起。

        

 

五、新的组件

1、Fragment

在Vue2中:组件必须有一个根标签。

在Vue3中:组件可以没有根标签,内部会将多个标签包含在一个Fragment虚拟元素中。

好处:减少标签层级,减小内存占用。

2、Teleport

(1)Teleport是一种能够将我们的组件html结构移动到指定位置的技术。

(2)语法:

<teleport to="移动位置">
	<div v-if="isShow" class="mask">
		<div class="dialog">
			<h3>我是一个弹窗</h3>
			<button @click="isShow = false">关闭弹窗</button>
		</div>
	</div>
</teleport>

 (3)代码展示

src/components/Dialog.vue

<template>
    <div>
        <button @click="isShow = true">点我弹个窗</button>
        <teleport to="body">
           <div class="mask" v-if="isShow">
            <div class="dialog">
                <h3>我是一个弹窗</h3>
                <h4>xxxxx</h4>
                <h4>xxxxx</h4>
                <h4>xxxxx</h4>
                <h4>xxxxx</h4>
                <button @click="isShow = false">关闭弹窗</button>
            </div>
           </div>
        </teleport>
    </div>
</template>

<script>
import { ref } from 'vue'
export default {
    name: 'Dialog',
    setup() {
        let isShow = ref(true)
        return { isShow }
    }
}
</script>

<style>
.mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0,0,0,0.5);
}
.dialog {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    text-align: center;
    width: 300px;
    height: 300px;
    background-color: green;
}
</style>

 

3、Suspense

(1)作用:

等待异步组件时渲染一些额外内容,让应用有更好的用户体验。

(2)使用步骤:

① 异步引入组件

import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))

② 使用Suspense包裹组件,并配置好default与fallback

<template>
	<div class="app">
		<h3>我是App组件</h3>
		<Suspense>
			<template v-slot:default>
				<Child/>
			</template>
			<template v-slot:fallback>
				<h3>加载中.....</h3>
			</template>
		</Suspense>
	</div>
</template>

(3)代码展示

  • src/App.vue
<template>
  <div class="app">
   <h3>我是App组件</h3>
   <Suspense>
      <template v-slot:defalut>
         <Child/>
      </template>
      <template v-slot:fallback>
         <h3>稍等,加载中...</h3>
      </template>
   </Suspense>
  </div>
</template>

<script>
// import Child from './components/Child.vue'   //静态引入
import {defineAsyncComponent} from 'vue'   //动态引入
const Child = defineAsyncComponent(()=>import('./components/Child'))        //异步引入
export default {
   name:'App',
   components:{Child},
}
</script>

<style>
.app {
   background-color: gray;
   padding:10px
}
</style>
  • src/components/Child.vue
<template>
  <div class="child">
    <h3>我是Child组件</h3>
    {{sum}}
  </div>
</template>

<script>
import {ref} from 'vue'
export default {
    name:'Child',
    async setup(){
      let sum = ref(0)
      let p = new Promise((resolve,reject)=>{
        setTimeout(()=>{
          resolve({sum})
        },1000)
      })
      return await p
    }
   
}
</script>

<style>
.child {
    background-color: skyblue;
    padding: 10px;
}
</style>

六、其他

1、全局API的转移

(1)Vue2.x有许多全局API和配置

         例如:注册全局组件、注册全局指令等。

//注册全局组件
Vue.component('MyButton', {
  data: () => ({
    count: 0
  }),
  template: '<button @click="count++">Clicked {{ count }} times.</button>'
})

//注册全局指令
Vue.directive('focus', {
  inserted: el => el.focus()
}

(2)Vue3.0中对这些API做出了调整:

         将全局的API,即:Vue.xxx调整到应用实例(app)上

Vue2.x全局API

Vue3.0全局API

Vue.config.xxxapp.config.xxx
Vue.config.productionTip移除
Vue.componentapp.component
Vue.directiveapp.directive
Vue.mixinapp.mixin
Vue.useapp.use
Vue.prototypeapp.config.globalProperties

2、其他改变

(1)data选项应始终被声明为一个函数

(2)过渡类名的更改:

     ① Vue2.x写法

.v-enter,
.v-leave-to {
  opacity: 0;
}
.v-leave,
.v-enter-to {
  opacity: 1;
}

      ② Vue3.0写法:

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.v-leave-from,
.v-enter-to {
  opacity: 1;
}

(3)移除keyCode作为v-on的修饰符,同事也不再支持config.keyCodes

(4)移除v-on.native修饰符

        ① 父组件中绑定事件

<my-component
  v-on:close="handleComponentEvent"
  v-on:click="handleNativeClickEvent"
/>

       ② 子组件中声明自定义事件

<script>
  export default {
    emits: ['close']
  }
</script>

(5)移除过滤器(filter)

过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。

  • 14
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值