首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue将功能组件转换为Vue 3

Vue将功能组件转换为Vue 3
EN

Stack Overflow用户
提问于 2020-10-16 22:57:03
回答 1查看 3.2K关注 0票数 1

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

例如,我有这样的组件:

代码语言:javascript
复制
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了:

代码语言:javascript
复制
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?如何添加嵌套的span和类?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-17 05:51:11

样式

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

代码语言:javascript
复制
import './MyComponent.css'

props.name

您使用的是未声明的props.name,所以请确保将其添加到props

代码语言:javascript
复制
MyComponent.props = {
  //...
  name: {
    type: String,
    required: true,
  },
}

参数

  1. h()的第二个参数是一个属性对象,其中包括class,因此您将在class键下传递多个类名。
  2. h()的第三个参数可以是字符串、插槽或子元素数组,这些元素也是用h()创建的,因此可以通过将它们传递到数组中来嵌套<span>
代码语言:javascript
复制
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()调用的等价物:

代码语言:javascript
复制
const MyComponent = ({ name, width, title }) =>
  <div class={`main-${name} ${width && 'default-width'}`}>
    {title && <span>{title}</span>}
    <span> hello </span>
  </div>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64397420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档