2020年12月6日 星期日

[JS] 從網路上看到的小技巧文章整理

1. 過濾唯一值
    Set 
2. for loop 先需告長度,先緩存就不需每次都重算,強化性能
    let i = 0, length = array.length; i < length; i++
3. 短路求值
    原本的三元視情況改使用 && ||
4. 轉型成布林
    !!
5. 轉型成字串
    +''
6. 轉型成數字
    + 或 *1 或 ~~,但~~小數在會被捨去
7. 冪運算
    ** 及 <<
    例如 Math.pow(2,4) 等於 2**4 等於 2<<3
8. 快速取整 (無條件捨去)
    n|0
9. 自動類(class)綁定,通常是在 react 中
    使用箭頭函式,this.myMethod.bind(this) 變成 this.myMethod()
10. 截取陣列
    已知取頭幾個元素,直接 assign 該陣列長度
    slice() 速度更快。也可用負數取尾幾個元素
11. 加強格式化 JSON 易讀性
    JSON.stringify(value[, replacer[, space]])
    replacer 有篩選的意味,可以是數字、字串、布林、物件、undefined;space 控制格式
    
JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t')
12. 過濾 false 值
    .filter(Boolean)
13. 一次性函數
    var sca = function(){
        console.log('只出現一次') 
        sca = function(){
            console.log('剩下都是我')
        }
    }
    sca() // '只出現一次'
    sca() // '剩下都是我'
    sca() // '剩下都是我'
    sca() // '剩下都是我'

2020年9月14日 星期一

[Nuxt/API/Axios] SSR mode 自己寫的.js 寫 axios 要區別 baseURL / browserBaseURL

情境: 自己寫的 api folder / axiosInstance.js
因不是寫在 nuxt.config.js, 不能直接用

baseURL: process.env.BASE_URL : process.env.BROWSER_BASE_URL,
browserBaseURL: process.env.BROWSER_BASE_URL,

的方式,要改成

baseURL: process.server ? process.env.BASE_URL : process.env.BROWSER_BASE_URL,

2020年7月1日 星期三

[Nuxt/CSS] 只讓特定 page 或 layout 載入指定樣式 (bootstrap)

來源 https://stackoverflow.com/questions/44541872/changing-body-styles-in-vue-router
https://forum.vuejs.org/t/how-do-i-add-remove-classes-to-body/1219

因A專案沒有使用 bootstrap,
現在要直接在 A 專案資料夾中增加 B 專案,但要使用 BS,
且 url 為空時要預設轉導向 B 首頁
造成 A 專案會被 BS 蓋掉

解法:
B 專案的主 page
@import BS

( 這時如果沒有轉導向不會蓋掉 )

router 設定轉導後,
B 專案的主 page 改成
body.useBS{ @import BS }


B 專案的主 layout
beforeCreate () {
  document.body.className = 'useBS'
}

[API/JSON] 打 API 送出資料 NaN 的結果

被要求不要送出 null 當參數打 API 但可以送出 undefined
不過百思不得其解為何送出 NaN 卻是 null

ans:

JSON.stringify({ a: 1, b: NaN, c: '2', d: undefined, e: null})
// "{"a":1,"b":null,"c":"2","e":null}"

2020年6月30日 星期二

[Nuxt] config 檔與 css import 順序有關的警告 & .prettierrc 設定

先上解法
https://github.com/nuxt/nuxt.js/issues/4885
extractCSS: { ignoreOrder: true }

如果在 a.vue import 元件的順序為:

import a
import b

在 b.vue import 順序為:

import b
import a

如此就會報警告:
WARN  Error                                                                                                                                         friendly-errors 15:03:04

chunk 0 [extract-css-chunks-webpack-plugin]                                                                                                          friendly-errors 15:03:04
Conflicting order between:
...

.prettierrc 設定請參考 
它優先度高於 .vscode setting
最常用的例如
{
"semi": false,
"singleQuote": true,
"printWidth": 120
}

2020年4月28日 星期二

[JS] querySelectorAll 取得的 NodeList 是 array 嗎? Array.from()

直接用 Array.isArray('selectedName') 來看就可得知「不是」!
要用 array methods 操作它就要幫它整形

此方法除了轉型,且可以配合箭頭函示遍歷每個 element
(截自MDN)

Array.from([1, 2, 3], x => x + x);      
// [2, 4, 6]

// 產生數值序列
// 因為陣列中的每個位置都會被初始化為 `undefined`,
// 下方 `v` 會是 `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

2020年2月14日 星期五

[Vue] 避免快速連點

不想讓 user 快速連點觸發 API 的按鈕

<button
:disabled="disabledTrigger"
@click="preventDoubleClick()"
>
click!
</button>

data () {
return {
disabledTrigger: false,
}
},

methods: {
preventDoubleClick () {
let i = 1
this.disabledTrigger = true
const timer = setInterval(() => {
i = i + 1
if (i > 1) {
this.disabledTrigger = false
i = 1
clearInterval(timer)
}
}, 250)
} }

2020年2月11日 星期二

[Vue] vue-router 進入頁面若無帶 query 參數帶入指定 query

情境: 在任意網頁甚至主頁點選進入 /products
會沒有指定 query ( 如 /products?type=food ) 只進入 /products
使其固定帶上 query 方式如下

{
name: 'products',
path: `${rootPath}/products`,
component: () => import(/* webpackChunkName: "courses" */ '../pages/products/').then(m => m.default || m),
beforeEnter: (to, from, next) => {
if (!to.query.type) {
next({
path: to.path,
query: { type: 'food' }
})
}
next()
}
},

2020年1月9日 星期四

[Vue] 關於 v-for 產表單 v-model bind 自定義 dataName

參考自
https://forum.vuejs.org/t/v-model-with-dynamically-created-inputs-with-v-for/9556

這邊遇到問題: 想利用 v-for 產表單, 同時綁不同「已預設好名稱」的 key 。
原先讓 v-model 指向在 data 設好的 name = '', account = '' ... ,  (v-model = 'this.dataName')
但這只會指向記憶體位置的空字串

最後解決方案: data 建立一個物件, 內含符合自己命名的 key , value 為空 ,
並在 v-for items 的 items 塞對應的 key (String) 給 v-model 讀取
描述得不好, 直接上範

<div
v-for="(item, index) in fromApiData"
:key="index"
>
<label for="" class="label form__label w-4/5">{{ item.title }}</label>
<input
class="input form__input w-4/5"
type="text"
:placeholder="item.detail || '未設定'"
v-model="inputCatcher[item.model]"
/>
</div>

// 其他省略

data () {
return {
inputCatcher: {
name: '',
account: '',
},
}
},
computed: {
fromApiData () {
return [
{
title: '名稱',
detail: this.user.name, // user 為從 api 抓到的資料 // model: this.name 原本錯誤的ㄒ
model: 'name'
},
{
title: '帳號',
detail: this.user.account,
model: 'account'
},
]
}
},

[CSS] flex 分散對齊後,最後一行置左

用算的
https://juejin.im/post/5d4556a16fb9a06b2f5f93ff - juejin.im 木匠_随便说说

用 ::after
https://blog.csdn.net/erciyuan_nuonuo/article/details/71773557 - blog.csdn.net

其他狀況, 如子元素不等寬時
https://www.html.cn/web/css/11909.html - html.cn