爲了方便擴展,使用 v-for
循環渲染出按鈕,綁定切換搜索引擎的 method , 傳入不一樣名稱以區別搜索引擎。按鈕的樣式也動態綁定。javascript
輸入框動態綁定樣式,在點擊按鈕切換搜索引擎時,搜索框綁定的樣式對應的 data 改變。css
<template> <section id="search-wrapper"> <el-row class="search-wrapper-row"> <el-row style="margin-bottom: 10px"> <el-button size="mini" type="primary" v-for="(item, index) in source" @click="changeSource(item.name)" :key="index" :style=" `background:${item.color};border-color:${item.color}` " >{{ item.name }}</el-button > </el-row> <el-input :placeholder="searchbarStyle.placeholder" :class="searchbarStyle.className" v-model="searchValue" clearable> <el-button @click="submit" slot="append" icon="el-icon-search"></el-button> </el-input> </el-row> </section> </template>
datahtml
v-model
綁定的搜索內容methodsvue
changeSource 點擊按鈕時觸發,接收搜索引擎 name, 內部使用 Map,匹配對應的函數,在函數中更改 baseUrl 和 searchbarStyle,因爲在 template 動態綁定了 searchbarStyle,這樣就能根據所選擇的搜索類型改變搜索框的樣式了。java
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) }, }, }
在 searchbarStyle 對象中有個 className 字段,input 會動態綁定與之對應的 css class。好比選擇百度時對應 .baidu
, 選擇必應時對應 .bing
etc. 因爲使用了 scss 預處理器,經過 @each
循環它們就行了。git
$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 中還攜帶了其餘參數。web
數據能夠單獨抽離, 使用 export 導出並引入, 這樣 .vue
看起來不會太長,易於維護。npm
能夠綁定按下 enter 時發起搜索。數組
預覽地址app
若是你有建議歡迎指教,謝謝 💗