簡體   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