如何在less中使用@定义颜色变量

207 阅读1分钟

方法一:局部使用

@/assets/variables.less

@primary-blue: #1890ff;
@primary-white: #fff;

App.vue

<template>
  <div class="btn">按钮</div>
</template>
<style lang="less">
// 引入 variables.les
@import '~@/assets/variables.less';
.btn {
  width: 80px;
  height: 30px;
  border-radius: 10px;
  text-align: center;
  line-height: 30px;
  // 使用颜色变量
  color: @primary-white;
  background-color: @primary-blue;
}
</style>

方法二:全局使用

@/assets/index.less

@import './variables.less';
.btn {
  width: 80px;
  height: 30px;
  border-radius: 10px;
  text-align: center;
  line-height: 30px;
  color: @primary-white;
  background-color:@primary-blue;
}

main.js

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
// ◇引入全局样式
import '@/assets/index.less'
// 引入 自定义指令
// import Directive from './directive'
// Vue.use(Directive)

Vue.use(ElementUI);
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div class="btn">按钮</div>
</template>

image.png

其它方式实现颜色变量

:root {
  --primary-color: #8890ff;
  --secondary-color: #fff;
}

.btn {
  width: 80px;
  height: 30px;
  border-radius: 10px;
  text-align: center;
  line-height: 30px;
  background-color: var(--primary-color);  
  color: var(--secondary-color);
}

页面引入使用方法同 @