返回
从Vue2到Vue3的迁移之旅(系列二)
前端
2023-09-19 02:26:17
16.内联模板 Attribute 非兼容
变化概览:
- 对内联特性的支持已被移除。
- 2.x 语法
- 在 2.x 中,Vue 为子组件提供了
<template>
标签,允许您在组件内部使用内联模板。例如:
<template> <div> <h1>{{ title }}</h1> <p>{{ content }}</p> </div> </template>
- 在 3.x 中,
<template>
标签已被移除,您需要使用<script setup>
标签来定义组件的模板。例如:
<script setup> const title = 'My Component'; const content = 'This is the content of my component.'; </script> <template> <div> <h1>{{ title }}</h1> <p>{{ content }}</p> </div> </template>
- 在 2.x 中,Vue 为子组件提供了
迁移指南:
- 将
<template>
标签替换为<script setup>
标签。 - 将
<template>
标签内部的内容移动到<script setup>
标签的template
选项中。 - 确保在
<script setup>
标签中定义组件的属性和方法。
17.Teleport 迁移
变化概览:
- Teleport API 已被重写,现在它是一个独立的包,名为
@vue/teleport
。 - 2.x 语法
- 在 2.x 中,您可以使用
teleport
指令将元素移动到另一个位置。例如:
<div> <teleport to="#app"> <p>This is a teleported element.</p> </teleport> </div>
- 在 3.x 中,您需要安装
@vue/teleport
包并将其注册为全局组件。然后,您可以使用<teleport>
组件来将元素移动到另一个位置。例如:
<div> <teleport to="#app"> <p>This is a teleported element.</p> </teleport> </div>
- 在 2.x 中,您可以使用
迁移指南:
- 安装
@vue/teleport
包。 - 在您的 Vue 实例中注册
Teleport
组件。 - 将
<teleport>
指令替换为<teleport>
组件。
18.provide/inject的变化
变化概览:
provide
和inject
API 已被重写,现在它们更加强大和灵活。- 2.x 语法
- 在 2.x 中,您可以使用
provide
和inject
API 来共享数据和方法。例如:
// Parent component export default { provide() { return { message: 'Hello, world!' } } } // Child component export default { inject: ['message'], render() { return <p>{ this.message }</p> } }
- 在 3.x 中,您需要使用
provide
和inject
函数来共享数据和方法。例如:
// Parent component export default { setup() { const message = provide('message', 'Hello, world!') } } // Child component export default { setup() { const message = inject('message') } render() { return <p>{ message }</p> } }
- 在 2.x 中,您可以使用
迁移指南:
- 将
provide
和inject
API 替换为provide
和inject
函数。 - 在
setup
函数中调用provide
函数来共享数据和方法。 - 在
setup
函数中调用inject
函数来获取共享的数据和方法。
19.scoped样式在Vue3中的使用
变化概览:
- scoped样式现在是一个独立的包,名为
@vue/component-compiler-utils
。 - 2.x 语法
- 在 2.x 中,您可以使用
<style scoped>
标签来定义scoped样式。例如:
<style scoped> .my-component { color: red; } </style>
- 在 3.x 中,您需要安装
@vue/component-compiler-utils
包并将其注册为全局组件。然后,您可以使用<style scoped>
标签来定义scoped样式。例如:
<style scoped> .my-component { color: red; } </style>
- 在 2.x 中,您可以使用
迁移指南:
- 安装
@vue/component-compiler-utils
包。 - 在您的 Vue 实例中注册
ComponentCompilerUtils
组件。 - 将
<style scoped>
标签替换为<style scoped>
标签。