繁体   English   中英

Vue 将功能组件转换为 Vue 3

[英]Vue convert functional component to Vue 3

我想将我的 Vue 2 功能组件迁移到 Vue 3。我阅读了他们的官方文档,但不明白。

例如,我有这个组件:

module.exports = (name, path, ariaLabel) => `<template functional>
  <div
    :class="['main-${name}', props.width ? 'default-width' : undefined]"
  >
  <span  v-if="title">${title}</span>
  <span> hello </span>
  </div>
</template>

<script>
export default {
  name: 'test-${name}',
  props: {
    width: {
      type: [Number, String],
      default: null
    },
    title: {
      type: String,
      required: false
    },
  }
}
</script>
<style src="./style.css"/>
`

我已经转换到 Vue 3 这么远了:

import { h } from 'vue'

const MyComponent = (props, context) => {
    return h(`div${props.name}`, context.attrs, context.slots)
}

MyComponent.props = {
    width: {
        type: [Number, String],
        default: null
    },
    title: {
        type: String,
        required: false
    },
}

import styles from './style.css';

export default MyComponent;

如何正确导入 CSS? 我将如何添加嵌套的跨度和类?

样式

可以将外部 CSS 文件导入到文件中,这些样式将自动应用于组件:

import './MyComponent.css'

props.name

您正在使用未声明的props.name ,因此请确保将其添加到props

MyComponent.props = {
  //...
  name: {
    type: String,
    required: true,
  },
}

h()参数

  1. h()的第二个参数是一个属性对象,其中包括class ,因此您可以在class键下传递多个类名。
  2. h()的第三个参数可以是字符串、槽或子元素数组,它们也是用h()创建的,因此您可以通过将它们传递到数组中来嵌套<span>
import { h } from 'vue'

const MyComponent = ({ name, width, title }) =>
  h(
    'div',

    // 1
    {
      class: `main-${name} ${width && 'default-width'}`
    },

    // 2
    [
      title && h('span', null, title), // conditional on `title`
      h('span', null, ' hello ')
    ]
  )

演示

JSX

使用 Vue CLI 生成的项目也支持开箱即用的JSX ,考虑到它与原始 HTML 的接近程度,这可能更直接。 这相当于上面的h()调用:

const MyComponent = ({ name, width, title }) =>
  <div class={`main-${name} ${width && 'default-width'}`}>
    {title && <span>{title}</span>}
    <span> hello </span>
  </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM