Vue3 从 Vue 2 迁移

181 阅读1分钟

事件 API

我们整个从实例中移除了 $on$off$once 方法,$emit 仍然是现有 API 的一部分,因为它用于触发由父组件以声明方式附加的事件处理程序

迁移策略

例如,可以通过使用实现事件发射器接口的外部库来替换现有的 event hub mitt

Install

This project uses node and npm. Go check them out if you don't have them locally installed.

$ npm install --save mitt

Then with a module bundler like rollup or webpack, use as you would anything else:

// using ES6 modules
import mitt from 'mitt'

// using CommonJS modules
var mitt = require('mitt')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script>

You can find the library on window.mitt.

Usage

import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

过滤器(removed)

在 3.x 中,过滤器已删除,不再支持。相反地,我们建议用方法调用或计算属性替换它们。

片段

在 3.x 中,组件现在可以有多个根节点!但是,这确实要求开发者明确定义属性应该分布在哪里。

<!-- Layout.vue -->
<template>
  <header>...</header>
  <main v-bind="$attrs">...</main>
  <footer>...</footer>
</template>