[译] Vue 3 迁移策略 —— 内联模板属性(移除)

1,194 阅读1分钟

需要调研 vue 2 到 vue 3 的迁移方案,来做内部分享。

我看网上貌似目前只有一人翻译了,翻译了前几章。

但是我着急用,只能自己翻了。译者四级没过,全靠有道和谷歌了。

vue 3 官方文档原文—— inline template attribute

概览

内联模板功能已移除

2.x 语法

在2.x 中,Vue 在子组件上提供了 inline-template 属性,子组件将会使用其里面的内容作为模板,而不是将其作为被分发的内容。

<my-component inline-template>
  <div>
    <p>These are compiled as the component's own template.</p>
    <p>Not parent's transclusion content.</p>
  </div>
</my-component>

3.x Syntax

功能已移除,不在支持此功能

迁移策略

inline-template 的大多数用例都假定没有构建工具的设置,所有模板都直接写在 HTML 页面内。

选项 1:使用 <script> 标签

在这种情况下,最直接的解决方法是使用 <script> 替代:

<script type="text/html" id="my-comp-template">
  <div>{{ hello }}</div>
</script>

在组件中,使用选择器定位模板:

const MyComp = {
  template: '#my-comp-template'
  // ...
}

这不需要任何构建设置,可以在所有浏览器中使用,也不受任何 in-DOM HTML 解析警告(例如,您可以使用 camelCase 属性名称),并且可以在大多数 IDE 中突出显示正确的语法。在传统的服务器端框架中,可以将这些模板分为服务器模板部分(包含在主 HTML 模板中),以实现更好的可维护性。

选项2:默认插槽

先前使用的组件inline-template也可以使用默认插槽进行重构-这使得数据作用域更加明确,同时保留了内联编写子内容的便利:

<!-- 2.x Syntax -->
<my-comp inline-template :msg="parentMsg">
  {{ msg }} {{ childState }}
</my-comp>

<!-- Default Slot Version -->
<my-comp v-slot="{ childState }">
  {{ parentMsg }} {{ childState }}
</my-comp>

现在,该子级(而不是不提供模板)应该呈现默认的广告位*:

<!--
  in child template, render default slot while passing
  in necessary private state of child.
-->
<template>
  <slot :childState="childState" />
</template>

注意:在3.x版本中,可以使用原生片段作为插槽的根节点!