啊
发现问题的过程
在使用Card组件时有一个需求,就是需要将card组件的标题下方的横线缩短。
为了完成这一需求,首先只能是对card组件的标题栏进行自定义样式修改了。而修改也很简单,我只需要在页面绑定headStyle就行了。
//ChartCard组件
<template>
<Card :title="growDate + '最新情报'" :bordered="false" :headStyle="headStyle">
<div ref="chartRef" :style="{ height, width }"></div>
</Card>
</template>
<script setup lang='ts'>
const headStyle = ref('margin:0 20px;boxSizing:border-box')
</script>
但我发现其他组件也要改,于是我决定把headStyle写在父页面,然后通过props传入。如下:
//父页面
<template>
<div>
<GrowCard :headStyle="headStyle" />
<ChartCard :headStyle="headStyle" />
<div >
</div>
</div>
</template>
<script setup lang='ts'>
import GrowCard from './GrowCard.vue'
import ChartCard from './ChartCard.vue'
import { ref } from
const headStyle = ref('margin:0 20px;box-sizing:border-box;')
</script>
这时ChartCard组件出现报错:
不能将类型“string”分配给类型“CSSProperties”。ts(2322)
index.d.ts(14, 13): 所需类型来自属性 "headStyle",在此处的 "Partial<{ loading: boolean; bordered: boolean; bodyStyle: CSSProperties; headStyle: CSSProperties; hoverable: boolean; }> & Omit<Readonly<ExtractPropTypes<{ prefixCls: StringConstructor; ... 15 more ...; onTabChange: { ...; }; }>> & VNodeProps & AllowedComponentProps & ComponentCustomProps, "loading" | ... 3 more ....." 类型上声明该属性
解决问题
我搜索了一下,CSSProperties是vue中带有的一种数据类型,在使用这个类型时需要先通过vue引入,然后该类型数据的书写方式同json,如下:
//父页面
<template>
<div>
<GrowCard :headStyle="headStyle" />
<ChartCard :headStyle="headStyle" />
<div >
</div>
</div>
</template>
<script setup lang='ts'>
import GrowCard from './GrowCard.vue'
import ChartCard from './ChartCard.vue'
import { CSSProperties } from 'vue'
const headStyle: CSSProperties = {
margin:'0 20px',
boxSizing:'border-box',
}
</script>
而且在引用时不需要使用ref声明,否则报错:
当然,到这一步还没完成,系统还有一个报错:
这个时候还需要修改ChartCard组件中的声明方式:
//ChartCard组件
defineProps({
headStyle:{
//headStyle是个对象,并将其类型断言为CSSProperties
type: Object as PropType<CSSProperties>,
default:() => ({})
},
});
ChartCard组件整体代码:
//ChartCard组件
<template>
<Card :title="growDate + '最新情报'" :bordered="false" :headStyle="headStyle">
<div ref="chartRef" :style="{ height, width }"></div>
</Card>
</template>
<script setup lang='ts'>
import { basicProps } from './props';
import { Card } from 'ant-design-vue'
import { growDate } from '../data';
import { useECharts } from '/@/hooks/web/useECharts';
import { onMounted, ref, Ref , CSSProperties } from 'vue';
defineProps({
...basicProps,
loading: Boolean,
width: {
type: String as PropType<string>,
default: '100%',
},
height: {
type: String as PropType<string>,
default: '300px',
},
headStyle:{
type: Object as PropType<CSSProperties>,
default:() => ({})
},
});
...
</script>