前端開發小技巧

前端開發小技巧(Vue、JS、CSS)

常用開發小技巧

寫在前面

JavaScript 篇

1.格式化金錢

const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

const money = ThousandNum(20190214);

// money => "20,190,214"

2.取整

代替正數的 Math.floor(),代替負數的 Math.ceil()

const num1 = ~~ 1.69;

const num2 = 1.69 | 0;

const num3 = 1.69 >> 0;

// num1 num2 num3 => 1 1 1

3.轉數值

只對 null 、"" 、false 、數值字符串 有效

const num1 = +null;

const num2 = +"";

const num3 = +false;

const num4 = +"169";

// num1 num2 num3 num4 => 0 0 0 169

4.精確小數

const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;

const num = RoundNum(1.69, 1);

// num => 1.7

5.取最小最大值

const arr = [0, 1, 2];

const min = Math.min(...arr);

const max = Math.max(...arr);

// min max => 0 2

6.判斷數據類型

function DataType(tgt, type) {

? ? const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();

? ? return type ? dataType === type : dataType;

}

DataType("young"); // "string"

DataType(20190214); // "number"

DataType(true); // "boolean"

DataType([], "array"); // true

DataType({}, "array"); // false

7.是否為空對象

const obj = {};

const flag = DataType(obj, "object") && !Object.keys(obj).length;

// flag => true

8.克隆數組

const _arr = [0, 1, 2];

const arr = [..._arr];

// arr => [0, 1, 2]

9.合并數組

const arr1 = [0, 1, 2];

const arr2 = [3, 4, 5];

const arr = [...arr1, ...arr2];

// arr => [0, 1, 2, 3, 4, 5];

10.去重數組

const arr = [...new Set([0, 1, 1, null, null])];

// arr => [0, 1, null]

11.截斷數組

const arr = [0, 1, 2];

arr.length = 2;

// arr => [0, 1]

12.交換賦值

let a = 0;

let b = 1;

[a, b] = [b, a];

// a b => 1 0

13.創建指定長度且值相等的數組

const arr = new Array(3).fill(0);

// arr => [0, 0, 0]

14.克隆對象

const _obj = { a: 0, b: 1, c: 2 }; // 以下方法任選一種

const obj = { ..._obj };

const obj = JSON.parse(JSON.stringify(_obj));

// obj => { a: 0, b: 1, c: 2 }

15.合并對象

const obj1 = { a: 0, b: 1, c: 2 };

const obj2 = { c: 3, d: 4, e: 5 };

const obj = { ...obj1, ...obj2 };

// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }

16.創建純空對象

const obj = Object.create(null);

Object.prototype.a = 0;

// obj => {}

17.優雅處理 Async/Await 參數

function AsyncTo(promise) {

? ? return promise.then(data => [null, data]).catch(err => [err]);

}

const [err, res] = await AsyncTo(Func());

Vue 篇

1.路由懶加載

import Vue from 'vue'

import Router from 'vue-router'

Vue.use(Router)

const router = new Router({

? routes: [

? ? {

? ? ? path: '/',

? ? ? component: () => import("xxx")

? ? }

]

})

2.頁面需要導入多個組件

原來的寫法

import titleCom from '@/components/home/titleCom'

import bannerCom from '@/components/home/bannerCom'

import cellCom from '@/components/home/cellCom'

components:{titleCom,bannerCom,cellCom}

利用 require.context 可以寫成

const path = require('path')

const files = require.context('@/components/home', false, /\.vue$/)

const modules = {}

files.keys().forEach(key => {

? const name = path.basename(key, '.vue')

? modules[name] = files(key).default || files(key)

})

components:modules

API 說明

實際上是 webpack 的方法,vue 工程一般基于 webpack,所以可以使用

require.context(directory,useSubdirectories,regExp) >

接收三個參數:

directory:說明需要檢索的目錄

useSubdirectories:是否檢索子目錄

regExp: 匹配文件的正則表達式,一般是文件名

3.動態組件

做一個 tab 切換時就會涉及到組件動態加載

<component v-bind:is="currentTabComponent"></component>

但是這樣每次組件都會重新加載,會消耗大量性能,所以 <keep-alive> 就起到了作用

<keep-alive>

? <component v-bind:is="currentTabComponent"></component>

</keep-alive>

這樣切換效果沒有動畫效果,這個也不用著急,可以利用內置的 <transition>

<transition>

<keep-alive>

? <component v-bind:is="currentTabComponent"></component>

</keep-alive>

</transition>

4.mixins

有些組件有些重復的 js 邏輯,如校驗手機驗證碼,解析時間等,mixins 就可以實現這種混入

const mixin={

? ? created(){

? ? ? this.dealTime()

? ? },

? ? methods:{

? ? ? dealTime(){

? ? ? ? console.log('這是mixin的dealTime里面的方法');

? ? ? }

? }

}

export default{

? mixins:[mixin]

}

5.為路徑設置別名

在開發過程中,我們經常需要引入各種文件,如圖片、CSS、JS 等,為了避免寫很長的相對路徑(../),我們可以為不同的目錄配置一個別名

// vue-cli 2.x 配置

// 在 webpack.base.config.js中的 resolve 配置項,在其 alias 中增加別名

resolve: {

? ? extensions: ['.js', '.vue', '.json'],

? ? alias: {

? ? ? 'vue$': 'vue/dist/vue.esm.js',

? ? ? '@': resolve('src'),

? ? }

? },

// vue-cli 3.x 配置

// 在根目錄下創建vue.config.js

var path = require('path')

function resolve (dir) {

? console.log(__dirname)

? return path.join(__dirname, dir)

}

module.exports = {

? chainWebpack: config => {

? ? config.resolve.alias

? ? ? .set(key, value) // key,value自行定義,比如.set('@@', resolve('src/components'))

? }

}

6.img 加載失敗

有些時候后臺返回圖片地址不一定能打開,所以這個時候應該加一張默認圖片

// page 代碼

<img :src="imgUrl" @error="handleError" alt="">

<script>

export default{

? data(){

? ? return{

? ? ? imgUrl:''

? ? }

? },

? methods:{

? ? handleError(e){

? ? ? e.target.src=reqiure('圖片路徑')

? ? }

? }

}

</script>

7.頁面統一判斷

在開發中經常會遇到權限判斷的問題,我們又不可能在每一個頁面的生命周期中去判斷一下,那樣太消耗時間了,處理方式:

router.beforeEach((to, from, next) => {

? myAccess.checkhaveAccess(to.path) === true ? next() : next('/forbid')

})

8.路由的項目啟動頁和 404 頁面

404 頁面指的是: 當進入一個沒有 聲明/沒有匹配 的路由頁面時就會跳轉到 404 頁面

export default new Router({

? routes: [

? ? {

? ? ? path: '/', // 項目啟動頁

? ? ? redirect:'/login'? // 重定向到下方聲明的路由

? ? },

? ? {

? ? ? path: '*', // 404 頁面

? ? ? component: () => import('./notfind')

? ? },

? ]

})

CSS 篇

1.使用 text-align-last 對齊兩端文本

在線演示

<div class="bruce flex-ct-x">

? ? <ul class="justify-text">

? ? ? ? <li>賬號</li>

? ? ? ? <li>密碼</li>

? ? ? ? <li>電子郵件</li>

? ? ? ? <li>通訊地址</li>

? ? </ul>

</div>

.justify-text {

? ? li {

? ? ? ? margin-top: 5px;

? ? ? ? padding: 0 20px;

? ? ? ? width: 100px;

? ? ? ? height: 40px;

? ? ? ? background-color: #f66;

? ? ? ? line-height: 40px;

? ? ? ? text-align-last: justify;

? ? ? ? color: #fff;

? ? ? ? &:first-child {

? ? ? ? ? ? margin-top: 0;

? ? ? ? }

? ? }

}

2.使用 color 改變邊框顏色

border 沒有定義 border-color 時,設置 color 后,border-color 會被定義成 color

場景:邊框顏色與文字顏色相同

.elem {

? border: 1px solid;

? color: #f66;

}

3.黑白圖像

讓你的彩色照片顯示黑白照片

img.desaturate {

? ? filter: grayscale(100%);

? ? -webkit-filter: grayscale(100%);

? ? -moz-filter: grayscale(100%);

? ? -ms-filter: grayscale(100%);

? ? -o-filter: grayscale(100%);

}

4.將圖片作為背景

當給頁面添加圖片時,尤其需要圖片是響應式的時候,最好使用 background 屬性來引入圖片,而不是 <img> 標簽

這看起來使用圖片會更復雜,但實際上它會使設置圖片的樣式變得更加容易。有了 background-size, background-position 和其它的屬性,保持或改變圖片原始尺寸和寬高比會更方便

background 引入圖片的一個缺點是頁面的 Web 可訪問性會受到輕微的影響,因為屏幕閱讀器和搜索引擎無法正確地獲取到圖像。這個問題可以通過 CSS object-fit 屬性解決,到目前為止除了 IE 瀏覽器其他的瀏覽器都可以使用 object-fit。

<section>

? ? <p>Img element</p>

? ? <img src="https://tutorialzine.com/media/2016/08/bicycle.jpg" alt="bicycle">

</section>

<section>

? ? <p>Div with background image</p>

? ? <div></div>

</section>

img {

? ? width: 300px;

? ? height: 200px;

}

div {

? ? width: 300px;

? ? height: 200px;

? ? background: url('https://tutorialzine.com/media/2016/08/bicycle.jpg');

? ? background-position: center center;

? ? background-size: cover;

}

section{

? ? float: left;

? ? margin: 15px;

}

5.保持選擇器的低權重

css 的選擇器并不都是平等的。當初學習 CSS 時,我總是認為選擇器會覆蓋它上面的所有內容。然而,情況并非如此

<a href='#' id='blue-btn' class="active">按鈕</a>

a{

? ? color: #fff;

? ? padding: 15px;

}

a#blue-btn {

? ? background-color: blue;

}

a.active {

? ? background-color: red;

}

我們希望.active類中設置的樣式會生效使按鈕變為紅色。但是它并不會起作用,因為按鈕在上面有一個ID選擇器,它同樣設置了background-color,ID選擇器具有更高的權重,所以按鈕的顏色是藍色的

權重也會疊加,于是a#button.active的權重要比a#button的高。一開始就使用高權重的選擇器會導致你在后面的維護中不斷的使用更高權重的選擇器

6.使用rem進行全局大小調整;使用em進行局部大小調整

在設置根目錄的基本字體大小后,例如html字體大小:15px;,可以將包含元素的字體大小設置為rem

article {? ?

? ? font-size: 1.25rem;?

}? ?

aside {? ?

? ? font-size: .9rem;?

}

將文本元素的字體大小設置為em

h2 {? ?

? ? font-size: 2em;?

}? ?

p {? ?

? ? font-size: 1em;?

}

參考鏈接

靈活運用 JS 開發技巧

靈活運用 CSS 開發技巧

我在 vue 開發中的小技巧

如何提升你的CSS技能,掌握這20個css技巧即可[完整版]

web進階知識

相關推薦

vue: 防止按鈕重復點擊

閱讀 966

兩年經驗面試阿里前端開發崗,已拿offer,這些知識點該放出來了

閱讀 5309

CSS外邊距塌陷問題

閱讀 95

ajax 工作原理

閱讀 43

給公司面試了100多個前端,心態差點給爺整崩了

閱讀 3409

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容