vue3安裝配置sass的詳細步驟
前言:
對于前端開發(fā)人員來說,css預處理的語言已經是家常便飯了,如sass,less等等,那么在vue3中該如何去使用sass呢?
首先看個最基礎的頁面,木有任何的樣式,接下來將一步一步的添加樣式!
<template> <div> 123456 </div> </template>
1. 安裝sass
npm install sass
2. 新建style目錄,存放scss文件
項目src文件下,新建styles目錄,當然位置自己隨意定,新建了這三個scss文件,下面我們對這三個文件進行一一解析。
constant.scss:用于放置項目中的sass變量,比如主題顏色,大字體的字號,小字體的字號等等,這里只是用于測試
$color-red: #ff0000; $large-size: 40px; $font-oblique: oblique;
index.scss:用于放置項目中自己封裝的一些常用的樣式,class類名,比如flex布局,定位,字體等等,這個只寫了一個
@import "./constant.scss"; .l-size { font-size: $large-size; }
variables.module.scss:用于scss變量的導出,大部分用于vue文件中js中使用
@import "./constant.scss"; :export { fontOblique: $font-oblique; }
3. main.ts
將我們封裝的公共的css樣式類名導入進main.ts文件中,這樣在所有的vue文件中,就可以隨意使用這些樣式了
嘗試一下~.~
<template> <div class="l-size"> 123456 </div> </template>
4. vite.config.ts
主要用途是將我們的constant.scss中的scss常量加載到全局,這樣我們可以在style標簽中,隨意使用這些scss常量
import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], resolve: { // Vite路徑別名配置 alias: { '@': path.resolve('./src') } }, /*主要看下面這段*/ css: { preprocessorOptions: { scss: { additionalData: '@import "@/styles/constant.scss";' } } } })
嘗試一下~.~
<template> <div class="l-size content"> 123456 </div> </template> <style lang="scss" scoped> .content { color: $color-red; } </style>
5. Test.vue
接下來,我們將 variables.module.scss中的變量導入到當前的vue文件中。
<script lang="ts" setup> import variables from "@/styles/variables.module.scss" console.log(variables) </script>
于是我們可以這么寫
<template> <div class="l-size content" :style="{fontStyle:variables.fontOblique}"> 123456 </div> </template> <script setup lang="ts"> import variables from "../styles/variables.module.scss" console.log(variables) </script> <style lang="scss" scoped> .content { color: $color-red; } </style>
或者利用computed
<template> <div class="l-size content" :style="getStyle"> 123456 </div> </template> <script setup lang="ts"> import {computed} from "vue" import variables from "../styles/variables.module.scss" const getStyle = computed(() => ({fontStyle: variables.fontOblique})) </script> <style lang="scss" scoped> .content { color: $color-red; } </style>
如此這樣~.~!
總結
到此這篇關于vue3安裝配置sass的文章就介紹到這了,更多相關vue3安裝配置sass內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決axios發(fā)送post請求返回400狀態(tài)碼的問題
今天小編就為大家分享一篇解決axios發(fā)送post請求返回400狀態(tài)碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08前端實現簡單的sse封裝方式(React hook Vue3)
這篇文章主要介紹了前端實現簡單的sse封裝方式(React hook Vue3),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08