vue(九)vue3新特性

vue3六大亮点:

  • 性能比Vue2强

  • 可以将无用模块去掉,仅打包需要的

  • 组合API

  • 碎片(fragment),portal传送门(teleport),悬念(suspense)

  • 更好的TS支持

  • 暴露了自定义渲染API

setup()

  • 在setup函数中声明对象,代替data()。ref声明简单对象,reactive声明复杂对象。

<template>
  <h3>{{ s1 }}</h3>
  <h3>{{ person.id }}</h3>
</template>

<script>
import {ref,reactive} from "vue"

export default {
    name: "App",
    setup(){
      const s1=ref("s1111")
      const person=reactive({
        id:1,
        name:"perter"
      })
      return{
        s1,person
      }
    }
}
  • 在setup()中声明methods

export default {
    name: "App",
    setup(){
      function clickHandler() {
        console.log(111);
      }
      return{
        clickHandler
      }
    }
}
  • 在setup()中使用props和context

props代替vue2的props,具有同样的组件交互功能

setup()是在组件 beforeCreate() 和 created() 时就已调用,所以无法在setup()中调用this,使用context代替this来获取组件的属性和上下文

setup(props,ctx){
      
      }
  • 在setup()中使用生命周期函数

    • 渲染时:beforeMount、mounted(网络请求一般放在mounted中),调用改为 OnBeforeMount, OnMounted

    • 更新时:beforeUpdate、updated,调用改为 OnBeforeUpdate, OnUpdated

    • 卸载时:beforeUnmount(卸载之前,把消耗性能的处理都删掉)、unmounted,调用改为 OnBeforeUnmount, OnUnmounted

    以前一个生命周期函数只能存在一个,现在可以定义多个

setup(){
    OnMounted(
        ()=>{console.log("...")}
    )

}
  • Provide/Inject

provide()inject() 可以实现嵌套组件之间的数据传递(上级向下级传递),不限制层级(跳过中间子组件)

父组件使用provide()向下传递数据,子组件使用 inject()获取上层传递过来的数据

这两个函数只能在 setup() 中使用

// 父组件传递
setup(){
    provide("msg","this is msg1")
}

// 子组件获取
setup(){
    const msg=inject("msg")
    return{
        msg
    }
}
  • fragment

不再限于模板中的单个根节点

 

posted @ 2023-07-10 19:27  huiyii  阅读(46)  评论(0编辑  收藏  举报