Vue Styled Components v1.4.0 - v1.7.0

86 阅读1分钟

仓库地址:github.com/vue-styled-…

文档地址:vue-styled-components.com/guide/basic…

近段时间版本升级比较频繁,所以多个版本一起合并说明了

Feature

自动添加前缀(Auto Prefixing)

vue-styled-components 会在编译 CSS 时自动添加浏览器私有前缀,这可以确保你的 CSS 规则在最常见的浏览器中兼容。

import { styled } from '@vue-styled-components/core';
const StyledDiv = styled.div`
  display: flex;
}`

// output:
// .styled-div {
//   display: -webkit-box;
//   display: -webkit-flex;
//   display: -ms-flexbox;
//   display: flex;
// }

支持使用 Tailwind CSS

vue-styled-components/coreTailwind CSS 无缝衔接,编写CSS更为方便。

<script setup lang="ts"> 
import styled, { tw } from '@vue-styled-components/core' 

const StyledDiv = styled.div`
  ${tw`w-20 h-20 bg-red-500`} 
` 
</script> 

<template> 
  <StyledDiv /> 
</template>

新的 props 传递方式

在之前的版本,传递自定义 props,必须给 styled 传递 Props Definition 对象:

<script setup lang="ts"> 
import { ref } from 'vue' 
import { styled } from '@vue-styled-components/core' 

const borderColor = ref('darkred') 
const inputProps = { borderColor: String } 

const StyledInput = styled('input', inputProps)` 
  border: 1px solid ${(props) => props.borderColor}; 
`  
</script> 

<template> 
  <StyledInput :borderColor="borderColor" />
</template>

新版本为组件新增了一个默认 props 属性,开发者可以通过这个属性传递自定义 props,会自动注入 Context

<script setup lang="ts">
import { ref } from 'vue'
import { styled } from '@vue-styled-components/core'

const borderColor = ref('darkred')
const StyledInput = styled.input`
  border: 1px solid ${(props) => props.borderColor};
`
</script>

<template>
  <StyledInput :props="{ borderColor }" />
</template>

TS 类型推断增强

  • 支持自定义 Theme 对象的类型定义

新建一个 typedef 文件,declare module 和 重新定义 DefaultTheme 即可,DefaultThem 默认类型是 Record<string, any>

// xxx.d.ts
import '@vue-styled-components/core';

export {};

interface Theme {
  primary: string;
}

declare module '@vue-styled-components/core' {
  export interface DefaultTheme extends Theme {}
}

定义了 Theme 类型后,在使用 styled 编写 CSS 使用 theme 时,就可以获得 ts 的类型提示

更多用法参考文档:vue-styled-components.com/