目录

Vue3学习笔记

Vue3学习笔记

Vite构建工具

优点:

  1. 开发环境中,无需打包操作,可快速的冷启动:Vite 启动开发服务器时无需打包,不用分析模块依赖和编译,而是利用浏览器原生支持 ES 模块的特性,当浏览器请求所需模块时再进行编译,实现按需动态编译。

  2. 轻量快速的热重载(HMR):当某个模块内容改变时,Vite 让浏览器重新请求该模块即可,无需像 Webpack 那样重新编译该模块的所有依赖,无论应用程序大小如何,都能实现极快的模块热重载。

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

    通过Vite创建一个Vue3的项目代码如下:

npm init vite-app 项目名称

注意:Vue3的组件中的中可以没有根标签了(即Vue2中必须有的

标签)

Setup配置项的使用:

1.概念:是Vue3.0中一个新的配置项,值为一个函数。

2.setup是所有Composition API(组合API)“ 表演的舞台”3.组件中所用到的:数据、方法等等,均要配置在setup中。

4.setup函数的两种返回值:

1.若返回一个对象,则对象中的属性、方法,在模板中均可以直接使用。(重点关注!)
2.若返回一个渲染函数:则可以自定义渲染内容。(了解)

5.注意点:

 1.尽量不要与Vue2.x配置混用
       a.Vue2.x配置(data、methos、computed..)中可以访问到setup中的属性、方法.

       b.但在setup中不能访问到Vue2.x配置(data、methos、computed...)。
       c. 如果有重名,setup优先。
2.setup不能是一个async函数,因为返回值不再是return的对象,而是promise,模板看不到return对象中的属性。

ref函数的使用:

作用: 定义一个响应式的数据,即ref对象
语法:
    A.const xxx = ref(initValue)
    B.创建一个包含响应式数据的引用对象(reference对象)9
    C.JS中操作数据: xxx.value
    D.模板中读取数据: 不需要.value,直接:<div>{{xxx}}</div>

备注:

接收的数据可以是:基本类型、也可以是对象类型:

基本类型的数据:响应式依然是靠 0bject.defineProperty()的get与set 完成的。

对象类型的数据:内部“求助”了Vue3.0中的一个新函数---reactive 函数。

APP.vue问价代码如下:

<template>
  <div>
    <h1>姓名{{name}}</h1>
    <h1>年纪{{age}}</h1>
    <h1>工种{{job.type}}</h1>
    <h1>薪资{{job.salary}}</h1>
    <button @click.once="changeInfo">点击修改姓名年纪</button>
  </div>
</template>
<script>
  import {ref} from 'vue'
  export default {
    name:'App',
    setup(){
      //数据
      let name = ref('张三')
      let age = ref(18)
      let flag = ref('true')
      let job = ref({
        type: '前端工程师',
        salary: '30k'
      })
      //方法
      function changeInfo(){
        name.value = '李四',
        age.value = '30k',
        job.value.type ='后端工程师'
        job.value.salary ='20k'
        if (flag.value){
         alert('按钮只能点击一次')
          flag.value = !flag.value
          }
      }
      //返回setup中的数据和方法
      return{
        name,
        age,
        job,
        changeInfo,
        flag
      }
    }
  }
</script>

reactive 函数

  • 作用: 定义一个对象类型的响应式数据( 基本类型不要用它,要用 ref 函数 )
  • 语法:const 代理对象=reactive(源对象)接收一个对象(或数组),返回一个代理对象(proxy实例对象)
  • reactive定义的响应式数据是“深层次的”。
  • 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作

App.vue实例代码如下:

<template>
  <div>
    <h1>姓名{{p.name}}</h1>
    <h1>年纪{{p.age}}</h1>
    <h1>工种{{p.job.type}}</h1>
    <h1>薪资{{p.job.salary}}</h1>
    <h1>c的值为{{p.job.a.b.c}}</h1>
    <h1>爱好为{{p.hobby}}</h1>
    <button @click.once="changeInfo">点击修改姓名年纪</button>
  </div>
</template>
<script>
  import {ref,reactive} from 'vue'
  export default {
    name:'App',
    setup(){
      //数据
     /* let name = ref('张三')
      let age = ref(18)
      let flag = ref('true')
      let hobby = reactive(['上学','吃饭','打豆豆'])
      let job = reactive({
        type: '前端工程师',
        salary: '30k',
        a:{
          b:{
            c:666
          }

        }
      })*/
      let flag = ref('true')
      let person = {
        name:'张三',
        age:18,
        hobby:['上学','吃饭','打豆豆'],
        job:{
          type: '前端工程师',
          salary: '30k',
          a:{
            b:{
              c:666
            }
        }
      }
      }
        const p = reactive(person)
      //方法
      function changeInfo(){
        p.name = '李四',
        p.age= '30k',
        p.job.type ='后端工程师'
        p.job.salary ='20k'
        p.job.a.b.c=111
        if (flag.value){
         alert('按钮只能点击一次')
          flag.value = !flag.value
          }
        for (let i =0;i<p.hobby.length;i++){
          p.hobby[i] = p.hobby[i]+i
        }
      }
      //返回setup中的数据和方法
      return{
        name,
        p,
        flag,
        changeInfo
      }
    }
  }
</script>

reactive函数与ref函数对比 :

。从定义数据角度对比:

ref用来定义:基本类型数据。

reactive用来定义:对象(或数组)类型数据,

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

从原理角度对比:

ref通过 object.defineProperty()的 get 与 set 来实现响应式(数据劫持)。

reactive通过使用Proxy来实现响应式(数据劫持),并通过Reflect操作源对象内部的数据。

从使用角度对比:

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

    reactive定义的数据:操作数据与读取数据:均不需要.value。

setup函数两个需要注意的点为:

  • setup执行的时机

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

  • setup的参数

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

    。context:上下文对象

    atrs:值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于 this.attrs.

    slots:收到的插槽内容,相当于 this.

    s l o t s e m i t : 分发自定义事件的函数 , 相当于 t h i s . slots emit: 分发自定义事件的函数,相当于 this.

    s

    l

    o

    t

    se

    mi

    t

    :

    分发自定义事件的函数

    ,

    相当于

    t

    hi

    s

    . emit

computed计算属性函数

1.与vue2.x版本中的功能一致

写法为:
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]}
})

代码示例demo.vue组件如下:

<template>
    <div>
      <h1>姓名{{person.name}}</h1>
      <h1>年纪{{person.age}}</h1>
      <slot name="slt"></slot>
      <h1>信息是{{person.message}}</h1>
      <h1>学校是{{person.school}}</h1>
      <button @click="changeInfo">点击显示信息</button>
      <slot></slot>

      <hr/>
      <h1>全部信息是{{person.fullName}}</h1>
    </div>
  </template>
 <script>
 import {reactive,computed} from 'vue'
    export default{
      // eslint-disable-next-line vue/multi-word-component-names
        name:'demo',
        props:[
            'msg',
            'school'
        ],
        emits:['showMSG'],

    setup(props,context){
        let person = new reactive({
            name: '张三',
            age: 18,
            message:'',
            school:'',

        })
        //计算属性,传入函数(此时为简写形式,没有考虑计算属性被修改的情况)
        //person.fullName = computed(()=>{return person.name + '-' + person.school})


      person.fullName = computed({  //考虑了计算属性被修改的情况
          get(){
            return person.name + '-' + person.school
          },
          set(value){
            person.Name =value.split('-')[0]
            person.school =value.split('-')[1]
          }
        })

        function changeInfo() {
            person.message = props.msg
            person.school = props.school
            console.log(context)
            context.emit('showMSG','jjjj')
        }
        return {
          person,
          changeInfo
        }
        }
    }
</script>

watch函数

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

2.两个小“坑”:

监视reactive定义的响应式数据时:oldValue无法正确获取,强制开启了深度监视(deep配置失效)。

    监视reactive定义的响应式数据中某个属性时:deep配置有效。

代码示例demo01.vue如下:

<template>
  <h1>值是{{sum}}---{{msg}}</h1>
  <button @click="sum++">点击sum++</button>
  <button @click="shouMessage">点击msg修改</button>
  <hr/>
  <h2>姓名{{person.name}}</h2>
  <h2>年纪{{person.age}}</h2>
  <h2>薪水{{person.job.salary}}</h2>
  <button @click="person.name +='-'">点击姓名改</button>
  <button @click="person.age +=1">点击年纪改</button>
  <button @click="person.job.salary++">加薪</button>

</template>

<script>
import {reactive, ref, watch} from 'vue'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "demo01",
  setup(){
    let sum = ref(0)
    let msg = ref("你好世界")
    let person = reactive({
      name:'李四',
      age:18,
      job:{
        salary:50
      }
    })
    //情况一:监视ref所定义的一个响应式数据
  /*  watch(sum,(newValue,oldValue)=>{
      console.log("sum被修改了",newValue,oldValue)
    })
*/
    //情况三:监视reactive所定义的一个响应式数据,注意:1.此处无法正确的获得oldValue。2.强制开启了深度监视

    watch(person,(newValue,oldValue)=>{
      console.log("姓名年纪是:",newValue,oldValue)
    }) //监视整个对象,默认开启deep

    //情况四:监视reactive所定义的一个响应式数据中的某个属性

  /*  watch(()=>{person.name},(newValue,oldValue)=>{
      console.log('person的name变化了',newValue,oldValue)
    })*/

    //情况五:深度监视对象
    watch(()=>person.job,(newValue,oldValue)=>{
      console.log('person的name变化了',newValue,oldValue)
    },{deep:true}), //此处由于监视的是reactive中定义的对象中的某个属性,所以deep配置有效
    watchEffect(() => { //只要该箭头函数中用到的都会被自动监视,即该函数监视所有数据  
      console.log(person.age)
    })

   function shouMessage(){
     msg.value = "张三"
   }
    //情况二:监视ref多定义的多个响应式数据

 /*   watch([sum,msg],(newValue,oldValue)=>{
      console.log("sum的值是" + newValue[0], "msg的值是" + newValue[1],"以前的值是"+oldValue[0] + oldValue[1])
    },{immediate:true})*/
    return {
      sum,
      msg,
    shouMessage,
      person
    }
  }
}
</script>

<style scoped>

</style>

watchEffect函数

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

。waichEtec的喜路是:不用指明监投哪个属性,监视的回调中用到个属性,那监投哪个属性,

。watchEffect有点像compued:

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

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

自定义hook函数

  1. 什么是hook?–本质是一个函数,把setup函数中使用的Composition APl行了封装。
   2. 类似于vue2.x中的mixin。
   3.自定义hook的优势: 复用代码,让setup中的逻辑更清楚易懂。

代码demo02.vue示例如下:

<template>
  <h1>当前鼠标的坐标是X:{{point.pointX}}  Y:{{point.pointY}}</h1>
</template>

<script>

import usePoint from "../hooks/usePoint";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "demo02",
  setup(){
    let point = usePoint()

    return{
      point
    }
  }
}
</script>

<style scoped>

</style>

usePoint.js文件代码如下:

import {onBeforeUnmount, onMounted, reactive} from 'vue'

export default function (){
    let point = reactive({
        pointX: 0,
        pointY: 0,
    })
    function geyXY(event){
        point.pointX = event.clientX
        point.pointY = event.clientY

    }
    onMounted(()=>{
        window.addEventListener('click',geyXY)
    })
    onBeforeUnmount(()=>{
        window.removeEventListener('click',geyXY)
    })

    return point
}

toRef与toRefs函数

作用:创建一个ref对象,其value值指向另一个对象中的某个属性!

语法:const name =toRef(person,‘name’)

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

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

示例demo03的代码如下:

<template>
  <h2>person对象的数据是{{person}}</h2>
  <h2>姓名{{name}}</h2>
  <h2>年纪{{person.age}}</h2>
  <h2>薪水{{salary}}</h2>
  <button @click="person.name +='-'">点击姓名改</button>
  <button @click="person.age +=1">点击年纪改</button>
  <button @click="person.job.salary++">加薪</button>

</template>

<script>
import {reactive,  toRef,toRefs} from 'vue'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "demo03",
  setup() {

    let person = reactive({
      name: '李四',
      age: 18,
      job: {
        salary: 50
      }
    })

    return {
     person,
      name:toRef(person,"name"), //返回出常用的属性
      salary: toRef(person.job,"salary") ,//返回出常用的属性
      ...toRefs(person) //自动解析person的所有属性并交出去
    }
  }

}
</script>

<style scoped>

</style>

readonly与shallowReadonly函数

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

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

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

toRaw与markRaw函数

toRaw:

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

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

markRaw:

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

。应用场景:

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

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

customRef自定义Ref

作用:创建一个自定义的ref,并对其依赖项跟踪和更新触发进行显示控制,同时可借助定时器实现防抖效果。

App.Vue示例代码如下

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

</template>
<script>
  import {customRef} from 'vue'
  export default {
    name:'App',
    setup(){
      function myRef(value){
        let timer
          return customRef((track,trigger)=>{
            return{
              get(){
                track()//追踪数据的变化
                return value
              },
              set(newValue){
                clearTimeout(timer)
                timer = setTimeout(()=>{
                  value = newValue //跟新值
                  trigger() //通知vue重新解析模板
                },1000)

              }
            }
          })
      }
      let keyword = myRef('你好世界')
      return{
        keyword
      }
    }

  }
</script>

provide与inject函数

作用:实现**祖孙**组件间通信
套路:父组件有一个 provide选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据

具体写法:

祖组件中:

setup(){
    lwt car = reactive({name:'宝马',price:'40w'})
    provide('car',car)
}

孙组件中:

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

son.vue组件代码如下:

<template>
  <h1>我是son组件,收到的数据是{{car}}</h1>
</template>

<script>
import {inject} from 'vue'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "son",
  setup(){
    let car =inject('car')
    return {  //return返回时要带上大括号,否则模板收不到数据
      car
    }
  }
}
</script>

<style scoped>

</style>

App.vue组件代码如下:

<template>
  <div>

    <h1>我是App组件我这里的car是{{car}}</h1>
    <son/>
  </div>

</template>
<script>
import { reactive,provide} from 'vue'
import son from "@/components/son";
  export default {
    name:'App',
    // eslint-disable-next-line vue/no-unused-components
    components:{son},
    setup(){
     let car = reactive({
       name: '宝马',
       price:'60w'
     })
      provide('car',car)
      return{
        car
      }
    }
  }
</script>

Teleport标签的使用

概念:是一种能够将我们的组件html结构移动到指定位置的技术

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

代码示例如:

<template>
  <div>
    <h1>我是App组件我这里的car是{{car}}</h1>
    <button @click="isshow = true">点我显示弹窗</button>
    <teleport to="body">
      <div v-show="isshow" class="color">
        <input type="text" placeholder="请输入名称">
        <input type="text" placeholder="请输入密码">
        <h1>内容一</h1>
        <h1>内容二</h1>
        <h1>内容三</h1>
        <button @click="isshow = false">点我关闭弹窗</button>
      </div>
    </teleport>
    <son/>
  </div>

</template>
<script>
import { ref,reactive,provide} from 'vue'
import son from "@/components/son";
  export default {
    name:'App',
    // eslint-disable-next-line vue/no-unused-components
    components:{son},
    setup(){
     let car = reactive({
       name: '宝马',
       price:'60w'
     })
      let isshow = ref(false)
      provide('car',car)
      return{
        car,
        isshow
      }
    },
    
  }
</script>
<style>
.color{
  background-color: #42b983;
  text-align: center;
  width: 300px;
  width: 300px;
}
</style>

  width: 300px;
  width: 300px;
}
</style>

suspense标签的使用

https://i-blog.csdnimg.cn/direct/6424ad0c6049420bb04678e95f08ed0b.png#pic_center