今天項目裏的實習生在作搜索功能時,導航欄的搜索框與搜索頁面的搜索框,在內容上居然是各自獨立的。。。。。
vue
不管他怎麼鼓搗,在搜索欄上進行搜索,搜索頁面都沒有任何反應。他解釋說由於是兩個獨立的組件且不構成父子關係,因此沒法進行值的傳遞共用,即使使用路由傳參,也就第一次能獲取到並觸發請求,後續搜索框再搜索內容,也沒法再次觸發搜索請求(其實,watch是能夠作到的。。。。)
ios
考慮到整個項目的統一性,以及將來的需求可變性(簡單來講,就是以防萬一產品又出幺蛾子),整個項目的搜索功能,我更傾向於用vuex來作
vuex
經過vuex來實現全局搜索功能的數據共用,假設你已經學過10分鐘的vuex(徹底沒學過的。。。先去看個10分鐘教程先)
axios
<!--首先編寫一個簡單的搜索模塊-->
const search = {
state: {
searchKey: ''
},
mutations: {
SET_SEARCH_KEY(state,key) {
state.searchKey = key
}
},
actions: {
setSearchKey(context,key) {
context.commit('SET_SEARCH_KEY',key)
}
}
}
export default search
複製代碼
<!--再將這個search模塊導入到store文件中-->
import Vue from 'vue'
import Vuex from 'vuex'
import search from './modules/search'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
search
}
})
<!--上面的寫法可能跟你看的新手教程不太同樣,由於實際項目裏須要用到vuex的地方蠻多的,所以總體內容量也比較大,因此通常都會採用分modules的形式,方便管理也方便後續繼續擴展-->
export default store
複製代碼
<!--最後就是在main.js中註冊它啦-->
import Vue from 'vue'
import router from './router'
import store from './store'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
複製代碼
到目前爲止,簡單的搜索模塊就作好了,那麼該如何使用呢?
分紅兩部分,一個是導航欄有搜索框,一個是搜索頁有搜索框也有搜索結果列表bash
<!--假設這裏是導航欄的搜索框-->
<template>
<div>
<input v-model="inputKey" @keyup.enter.native="handleKey"/>
</div>
</template>
<script>
export default {
data() {
return {
inputKey: ''// 這裏就是搜索的關鍵字
}
},
methods: {
handleKey() {
// 在這裏,調用store裏search模塊的setSearchKey方法
this.$store.dispatch('setSearchKey', this.inputKey)
}
}
}
<!--基本邏輯就是,在導航欄的搜索框裏輸入內容,點擊回車,觸發search()方法,調用store裏search模塊的setSearchKey方法,最終實現關鍵字searchKey的改變-->
</script>
複製代碼
<!--假設這裏是搜索頁的結果列表-->
<template>
<div>
<ul>
<li v-for="item in list" :key="item">{{item}}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: []// 結果列表
searchText: ''// 通常咱們不建議直接修改store裏的值,所以最好用另外一個變量儲存
}
},
computed: {
<!--實時獲取store裏的searchKey-->
searchKey() {
this.$store.state.search.searchKey
}
}
watch: {
<!--監聽searchKey,一旦該值有變化,馬上觸發相應操做-->
searchKey(val){
this.searchText = val
this.search()
}
}
methods: {
search() {
// 在這裏,真正地向後臺發起請求
axios.get(url,this.searchText).then((res) => {
this.list = res.list
})
}
}
}
</script>
複製代碼
到這裏爲止,就能夠成功實現,在導航欄的搜索框進行搜索,搜索頁面也能馬上顯示最新內容(即便兩個組件之間不構成父子組件),例如掘金的導航欄搜索, 底下的結果列表的變化app