1 先给vue新增loadmore指令
// main.js 中载入指令文件
import '@/utils/element-loadmore.js'
// utils/element-loadmore.js 中添加loadmore指令
import Vue from 'vue'
Vue.directive('loadmore', {
bind(el, binding) {
const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
SELECTWRAP_DOM.addEventListener('scroll', function() {
const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight
if (CONDITION) {
binding.value()
}
})
}
})
2 编写通用插件和引用
// 组件 RemoteSelectSearch.vue(有些参数没有抽取和添加,可自行优化)
<template>
<el-select
v-model="selectVal"
v-loadmore="loadMore"
clearable
filterable
:placeholder="placeholder"
remote
:remote-method="remoteMethod"
@visible-change="getEnterpriseName"
@change="val => { $emit('selectChangeValue', val) }"
>
<el-option
v-for="item in remoteItems"
:key="item.id"
:value="item.id"
:label="item.realName"
/>
</el-select>
</template>
<script>
export default {
props: {
initRemoteItems: { // 搜索选择列表
type: Array,
default: _ => []
},
initVal: { // 默认值
type: [Number, String],
default: null
}
},
data() {
return {
selectVal: this.initVal || null,
placeholder: '请输入关键词',
remoteApi: '/sPartyGroup/getSPartyGroupUsers',
remoteItems: this.initRemoteItems || [], // api远程返回的数据
searchIndex: 1, // api远程搜索页数
searchVal: '' // api远程搜索内容
}
},
watch: {
initVal(newVal) {
this.selectVal = newVal
},
initRemoteItems(newVal) {
this.remoteItems = newVal
}
},
methods: {
// 远程初始化搜索
getEnterpriseName() {
this.searchVal = ''
const params = {
pageIndex: 1,
pageSize: 20,
search: this.searchVal
}
if (this.searchIndex !== 1) return
this.remoteItems = []
this.$post(this.remoteApi, params, 1).then(({ data }) => {
this.remoteItems = data.records || []
console.log('this.remoteItems1', this.remoteItems)
})
},
// 远程滚动加载
loadMore() {
this.searchIndex++
const params = {
pageIndex: this.searchIndex,
pageSize: 20,
search: this.searchVal
}
this.$post(this.remoteApi, params, 1).then(({ data }) => {
(data.records || []).map((item) => {
this.remoteItems.push(item)
})
console.log('this.remoteItems2', this.remoteItems)
})
},
// 远程搜索
remoteMethod(inputValue) {
this.searchIndex = 1
this.searchVal = inputValue
const params = {
pageIndex: 1,
pageSize: 20,
search: this.searchVal
}
this.$post(this.remoteApi, params, 1).then(({ data }) => {
this.remoteItems = data.records || []
console.log('this.remoteItems3', this.remoteItems)
})
}
}
}
</script>
// 多个相同组件记得加key
<RemoteSelectSearch
key="secretary"
ref="secretary"
class="wd100"
:init-remote-items="[id: 1, realName: 'promise@w']"
:init-val="editData.secretaryId"
@selectChangeValue="val => { editData.secretaryId = val }"
/>