Vue3快速入门 2

226 阅读2分钟

这次官网关于 vue3 的文档信息量真的很大,可能我现在看确实有点 out 了, 不过好事不怕晚,精通 vue3 之后,能让我们的新的项目,开发的更加效率,出错也更少,代码可维护性也更高!再也不担心 vue2 上千行代码了

Teleport

这个能工类似于 react createPortal, 是将某一段html 挂载到指定的节点,对于 modal 组件非常适用, 举例

app.component('modal-button', {
  template: `
    <button @click="modalOpen = true">
        Open full screen modal! (With teleport!)
    </button>

    <teleport to="body">
      <div v-if="modalOpen" class="modal">
        <div>
          I'm a teleported modal! 
          (My parent is "body")
          <button @click="modalOpen = false">
            Close
          </button>
        </div>
      </div>
    </teleport>
  `,
  data() {
    return { 
      modalOpen: false
    }
  }
})

而且 Teleport 还能重复挂载同一个元素,结果是顺序添加在挂载的元素上

<teleport to="#modals">
  <div>A</div>
</teleport>
<teleport to="#modals">
  <div>B</div>
</teleport>

<!-- result-->
<div id="modals">
  <div>A</div>
  <div>B</div>
</div>

emits 定义

在vue2的版本里面,不会在组件中定义要抛出的 emits, 只能在组件内搜索 emits, 在 3 中,我们可以在 emits 属性上看到有哪些事件定义,

app.component('custom-form', {
  emits: ['inFocus', 'submit']
})

还可以验证 emits 的参数是否正确

app.component('custom-form', {
  emits: {
    // 没有验证
    click: null,

    // 验证 submit 事件
    submit: ({ email, password }) => {
      if (email && password) {
        return true
      } else {
        console.warn('Invalid submit event payload!')
        return false
      }
    }
  },
  methods: {
    submitForm(email, password) {
      this.$emit('submit', { email, password })
    }
  }
})

单文件组件<script setup>

这个是我认为非常棒的特性,有个这个特性,vue 的写法上更想了 react 的函数式组件, 以前import 的方法还要在 method 上再次赋值, 现在不用了

<script setup>
import { capitalize } from './helpers'
// 变量
const msg = 'Hello!'

// 函数
function log() {
  console.log(msg)
}
</script>

<template>
    <div>
        <div @click="log">{{ msg }}</div>
        <div>{{ capitalize('hello') }}</div>
    </div>
</template>

老版本 vue2 需要这样做

import { capitalize } from './helpers'
export default {
    methods: {
        capitalize,
    }
}
</script>

<template>
    <div>
        <div @click="log">{{ msg }}</div>
        <div>{{ capitalize('hello') }}</div>
    </div>
</template>

组件也是同样的道理,不用挂在 components 属性下了。总之就是大大简化了代码

defineProps 和 defineEmits

在 <script setup> 中必须使用 defineProps 和 defineEmits API 来声明 props 和 emits 官网中的必须的字样,我们必须注意

单文件组件样式特性

这块我看到一个非常棒的例子,可以直接在style标签里面动态绑定属性,来改变样式,这样的话也不用在元素上写 style 属性再去绑定了

<script setup>
const theme = {
  color: 'red'
}
</script>

<template>
  <p>hello</p>
</template>

<style scoped>
p {
  color: v-bind('theme.color');
}
</style>

reactive

我在 demo 中发现这个函数的使用,和 toRef 类似,但是并没有看到对应的解释。 直接搜索,在如下地址找到了v3.cn.vuejs.org/api/basic-r…

官网给的解释是: 返回对象的响应式副本, 所以从理解上看,ref 用于基础类型,reactive 用户对象类型

watch 可以侦听多个属性了

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  /* ... */
})

总结

看了下官方文档,着实东西不少,我没有全部列出来,挑选了一些,我觉得很重要的特性,

而且目前看,对于刚入口vue3的同学来说,官网还得反复观看,并且手上如果有vue2 的项目是最好的,

尝试将一些页面,重构成 vue3 的,活学活用。

下面,我也是准备将我的一个非常复杂的 vue2 页面改造成 vue3, 期待我的下一篇实战文章。