css-in-js 之 vue

CSS-in-JS就是可以使用JS来编写CSS样式,这原本是React的专属,现在可以在Vue中应用,依赖包:vue-styled-components

需要安装以下依赖:

$ npm i vue-styled-components @vue/babel-helper-vue-jsx-merge-props  @vue/babel-preset-jsx  --save-dev

并修改 babel.config.js

presets: [
		...,
		'@vue/babel-preset-jsx'
	],
1、组件封装
import styled from 'vue-styled-components';
import Vue from 'vue';

const img = require('@/assets/images/brain/data-changdao/scenic-point-bg.png');
const img1 = require('@/assets/images/brain/data-changdao/scenic-point.png');

// 通过 props 给组件传参,并动态的传递到css中
const div1 = styled('div', {
	width: {
		type: Number,
		default: 10
	}
})`
	width: ${props => props.width}rem;
	height: 0.62rem;
	margin-bottom: 0.6rem;
	padding: 0 0.36rem;
	background: url(${img}) no-repeat;
	background-size: contain;
`;
const div11 = styled.div`
	font-size: 0.38rem;
	font-family: PingFang SC;
	font-weight: 500;
	color: #FFFFFF;
`;
const div11_img = styled.img`
	width: 0.43rem;
	height: 0.4rem;
	margin-right: 0.17rem;
`;
const div11_span = styled.span`
	display: inline-block;
	width: 3.5rem;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
`;
const div12 = styled.div`
	font-size: 0.48rem;
	font-family: PingFang SC;
	font-weight: 600;
	color: #FFFFFF;
`;
const div12_span1 = styled.span``;
const div12_span2 = styled.span`
	font-size: 0.33rem;
	color: rgba(255, 255, 255, 0.6);
`;

export default Vue.component('Scenic', {
	props: {
		scenicTicketName: String,
		count: String,
		pe: String
	},
	render: function (h) {
		return (
			<div1 class='flex f-jc-sb' width={ this.pe }>
				<div11>
					<div11_img src={img1} />
					<div11_span>{ this.scenicTicketName }</div11_span>
				</div11>
				<div12>
					<div12_span1>{ this.count }</div12_span1>
					<div12_span2>{ this.pe }%</div12_span2>
				</div12>
			</div1>
		);
	}
});

2、父组件中使用
<ScenicContainer
	v-for="(item, index) in hotScenic"
	:key="index"
	:scenicTicketName="item.scenic_ticket_name"
	:count="item.count"
	:pe="item.pe"
/>

编译后的结果:
写在js中的样式都编译到一个随机名称的class中去了。

特点:将所有的css样式全部都编辑到一个随机名字的class中去了。相比于vue 的属性选择器,渲染速度要快一点。

你可能感兴趣的:(H5,javascript,vue.js,css)