我想把我的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?如何添加嵌套的span和类?
发布于 2020-10-17 05:51:11
样式
外部CSS文件可以导入到文件中,这些样式将自动应用于组件:
import './MyComponent.css'props.name
您使用的是未声明的props.name,所以请确保将其添加到props中
MyComponent.props = {
//...
name: {
type: String,
required: true,
},
}h()的第二个参数是一个属性对象,其中包括class,因此您将在class键下传递多个类名。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>https://stackoverflow.com/questions/64397420
复制相似问题