✍ 寫一個擴充套件性較強的搜尋主頁
阿新 • • 發佈:2020-06-12
## 前置
- 點選按鈕切換搜尋引擎
- 搜尋框跟隨切換改變樣式
- 使用 vue 最快了
![](https://gitee.com/guangzan/imagehost/raw/master/markdown/aweshome-search.gif)
## template
為了方便擴充套件,使用 `v-for` 迴圈渲染出按鈕,繫結切換搜尋引擎的 method , 傳入不同名稱以區別搜尋引擎。按鈕的樣式也動態繫結。
輸入框動態繫結樣式,在點選按鈕切換搜尋引擎時,搜尋框繫結的樣式對應的 data 改變。
```html
{{ item.name }}
```
## script
**data**
- baseUrl 搜尋引擎地址
- searchValue input `v-model` 繫結的搜尋內容
- searchbarStyle 搜尋框對應的樣式,值型別為 Object, 方便擴充套件不同搜尋框樣式
- source 按鈕的樣式即名稱,陣列物件, 方便按鈕擴充套件
**methods**
changeSource 點選按鈕時觸發,接收搜尋引擎 name, 內部使用 Map,匹配對應的函式,在函式中更改 baseUrl 和 searchbarStyle,由於在 template 動態綁定了 searchbarStyle,這樣就能根據所選擇的搜尋型別改變搜尋框的樣式了。
```javascript
export default {
data() {
return {
baseUrl: 'https://www.baidu.com/s?ie=UTF-8&wd=',
searchValue: '',
searchbarStyle: {
className: 'baidu',
placeholder: '百度一下,你就知道',
},
source: [
{
name: '百度',
color: '#2932E1',
},
{
name: '必應',
color: '#0c8484',
},
{
name: '搜狗',
color: '#FF6F17',
},
{
name: '谷歌',
color: '#4285F4',
},
{
name: 'NPM',
color: '#EA4335',
},
],
}
},
methods: {
changeSource(name) {
const actions = new Map([
[
'百度',
() => {
this.baseUrl = 'https://www.baidu.com/s?ie=UTF-8&wd='
this.searchbarStyle = {
className: 'baidu',
placeholder: '百度一下,你就知道',
}
},
],
[
'必應',
() => {
this.baseUrl = 'https://cn.bing.com/search?FORM=BESBTB&q='
this.searchbarStyle = {
className: 'bing',
placeholder: '必應搜尋',
}
},
],
[
'搜狗',
() => {
this.baseUrl = 'https://www.sogou.com/web?query='
this.searchbarStyle = {
className: 'sougou',
placeholder: '搜狗搜尋',
}
},
],
[
'谷歌',
() => {
this.baseUrl = 'https://www.google.com/search?q='
this.searchbarStyle = {
className: 'google',
placeholder: 'Google Search',
}
},
],
[
'NPM',
() => {
this.baseUrl = 'https://www.npmjs.com/search?q='
this.searchbarStyle = {
className: 'npm',
placeholder: 'Search Packages',
}
},
],
])
actions.get(name)()
},
submit() {
const url = this.baseUrl + this.searchValue
window.open(url)
},
},
}
```
## style
在 searchbarStyle 物件中有個 className 欄位,input 會動態繫結與之對應的 css class。比如選擇百度時對應 `.baidu`, 選擇必應時對應 `.bing` etc. 由於使用了 scss 前處理器,通過 `@each` 迴圈它們就好了。
```css
$sources-color: (
baidu: #2932e1,
bing: #0c8484,
sougou: #ff6f17,
google: #4285f4,
npm: #ea4335,
);
$source-list: baidu bing sougou google npm;
@each $source in $source-list {
.#{$source} {
.el-input-group__append,
input {
border-color: map-get($sources-color, $source);
&:hover {
border-color: map-get($sources-color, $source);
}
}
.el-icon-search {
color: map-get($sources-color, $source);
&:hover {
border-color: map-get($sources-color, $source);
}
}
}
}
```
## 最後
搜尋引擎在搜尋時並不是簡單的 baseUrl + 搜尋內容的形式,url 中還攜帶了其他引數。
資料可以單獨抽離, 使用 export 匯出並引入, 這樣 `.vue` 看起來不會太長,易於維護。
可以繫結按下 enter 時發起搜尋。
[預覽地址](https://guangzan.gitee.io/aweshome/#/)
如果你有建議歡迎指教,謝