Vue3如何根據(jù)搜索框內(nèi)容跳轉(zhuǎn)至本頁面指定位置
需求
需求:根據(jù)搜索框內(nèi)容跳轉(zhuǎn)至本頁面指定位置
搜索框是我們在開發(fā)各類項目中出現(xiàn)率很高的一個"組件",在element-plus中名為"自動補全輸入框",即我們可以根據(jù)輸入的內(nèi)容去檢索列表或者表格或者其他本頁面出現(xiàn)的元素,那我們應(yīng)該如何去實現(xiàn)這個行為呢?
思路
整體過程是這樣的:
點擊輸入框的內(nèi)容,頁面跳轉(zhuǎn)至指定的內(nèi)容位置
實現(xiàn)過程
①首先我們必須要在頁面中引入自動補全輸入框組件
template部分 <el-autocomplete v-model="state1" :fetch-suggestions="querySearch" class="inline-input w-50" placeholder="搜索" @select="handleSelect" @change='change'> </el-autocomplete> srcipt部分 import { onMounted, ref } from 'vue' interface RestaurantItem { value: string link: string } const state1 = ref('') const restaurants = ref<RestaurantItem[]>([]) const querySearch = (queryString: string, cb: any) => { const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants.value // call callback function to return suggestions cb(results) } const createFilter = (queryString: string) => { return (restaurant: RestaurantItem) => { return ( restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ) } } const loadAll = () => { return [ { value: 'vue', link: 'https://github.com/vuejs/vue' }, { value: 'element', link: 'https://github.com/ElemeFE/element' }, { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' }, { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' }, { value: 'vuex', link: 'https://github.com/vuejs/vuex' }, { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' }, { value: 'babel', link: 'https://github.com/babel/babel' }, ] } const handleSelect = (item: RestaurantItem) => { console.log(item) } onMounted(() => { restaurants.value = loadAll() })
需要解釋的是組件中的這個事件
select 點擊選中建議項時觸發(fā)
handleSelect 則是手動觸發(fā)選中建議事件
這一項是"點擊輸入框內(nèi)容"
②根據(jù)選中的內(nèi)容,在對應(yīng)的表格中查找
const handleSelect = (item: RestaurantItem) => { console.log(item) }
在這個函數(shù)中,我們可以log item,可以發(fā)現(xiàn)item就是loadAll中的內(nèi)容,我們可以給loadAll里的內(nèi)容都綁定一個id值,例如
{ id:1,value: 'vue', link: 'https://github.com/vuejs/vue' },
然后我們在對應(yīng)的表格的內(nèi)容也添加一個id,這里就不舉例了,至此,我們可以判斷,如果loadAll里的id==表格里某一項的id,那就是我們需要的對象
for(let i=0;i<表格長度;i++){ let id = 表格[i].id if (item.id == 表格[i].id) { document.getElementById(id).scrollIntoView(); }
③跳轉(zhuǎn)
document.getElementById(id).scrollIntoView();
整體的實現(xiàn)思路是:拿到搜索框選中的內(nèi)容的id,與此同時給表格中的每一項內(nèi)容都添加id,然后在select事件中,利用for循環(huán)去尋找搜索框id==表格內(nèi)容id的對象,最后是利用scrollIntoView()方法進(jìn)行跳轉(zhuǎn)
補充內(nèi)容
需要補充的是,如何獲取到對應(yīng)的元素?一是v-for循環(huán),給每個對象添加id,格式是v-for = value in 表格 :id="value.id"
二是通過綁定ref函數(shù)獲取
總結(jié)
到此這篇關(guān)于Vue3如何根據(jù)搜索框內(nèi)容跳轉(zhuǎn)至本頁面指定位置的文章就介紹到這了,更多相關(guān)Vue3跳轉(zhuǎn)指定位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用vue-cli+webpack搭建vue開發(fā)環(huán)境的方法
這篇文章主要介紹了使用vue-cli+webpack搭建vue開發(fā)環(huán)境的方法,需要的朋友可以參考下2017-12-12html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁
這篇文章主要為大家介紹了html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08