初识Vue(四)

49 阅读2分钟

Vue3相关

  • Performance:性能更比Vue 2.0强。
  • Tree shaking support:可以将无用模块“剪辑”,仅打包需要的。
  • Composition API:组合API
  • Fragment, Teleport, Suspense:“碎片”,Teleport即Protal传送门,“悬念”
  • Better TypeScript support:更优秀的Ts支持
  • Custom Renderer API:暴露了自定义渲染API

ref或者reactive

在2.x中通过组件data的方法来定义一些当前组件的数据

data() {
  return {
    name: 'iwen',     list: [],
  }
}

在3.x中通过ref或者reactive创建响应式对象

import { ref,reactive } from "vue" export default {
  name: 'HelloWorld',
  setup(){
      const name = ref("iwen")
      const state = reactive({
          list:[]
      })
    return{        
        name,         
        state     
    }
  }
}

methods中定义的方法写在setup()

在2.x中methods来定义一些当前组件内部方法

methods:{
    http(){}
}

在3.x中直接在setup方法中定义并return

setup() {
    const http = ()=>{         
        // do something   
    }
    return {
      http
    };
}

setup()中使用props和context

在2.x中,组件的方法中可以通过this获取到当前组件的实例,并执行data变量的修改,方法的调用,组件的通信等等,但是在3.x中,setup()在beforeCreate和created时机就已调用,无法使用和2.x一样的this,但是可以通过接收setup(props,ctx)的方法,获取到当前组件的实例和props

export default {
  props: {
    name: String,
  },
  setup(props,ctx) {
        console.log(props.name)     
        ctx.emit('event')
  },
}

在setup中使生命周期函

可以通过在生命周期钩子前面加上 “on” 来访问组件的生命周期钩子。

vue2 Apisvue3 Apis
beforeCreate
created
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeUnmountonBeforeUnmount
unmountedonUnmounted

Provide / Inject

  • provide()和 inject()可以实现嵌套组件之间的数据传递。
  • 这两个函数只能在 setup() 函数中使用。
  • 父级组件中使用 provide()函数向下传递数据。
  • 子级组件中使用 inject()获取上层传递过来的数据。
  • 不限层级
// 父组件
import { provide } from "vue"
setup() {
    provide("customVal", "我是父组件向子组件传递的值");
}
// 子组件
import { inject } from "vue"
setup() {
    const customVal = inject("customVal");     return {
      customVal
    }
}

Fragment

Fragment翻译为:“碎片”

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

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App" />
</template>