DeviceSelect.vue 2.84 KB
<template>	
    <el-select
	    v-model="selected"
    	filterable
	    remote
	    clearable
	    reserve-keyword
	    placeholder="请选择或输入搜索"
	    :remote-method="remoteMethod"
	    :loading="loading"
	    @visible-change="visibleChange"
	    @change="change"
	>	
		
	    <el-option
			v-for="item in options"
			:key="item.value"
			:label="item.label"
			:value="item.value">
	    </el-option>
	    <infinite-loading v-if="needInfinite" @infinite="infiniteHandler" ref="infiniteLoading">
			<span slot="no-more">没有更多数据了</span>
			<span slot="no-results">无结果</span>
		</infinite-loading>
  	</el-select>
</template>
<script>
	import {services} from '../../api'
	import InfiniteLoading from 'vue-infinite-loading';
	const DEVICE_SERVICE =  services.device

	export default{
		props:['label', 'prop', 'notPrepend', 'defaultValue', 'disabled'],
		data(){
			return {
				input: '',
				currentPage: 1,
				pageSize: 10,
				total: 0,
				maxPage: 1,
				selected: '',
				loading: false,
				options: [{}],
				needInfinite: false,
				params: {}
			}
		},
		created(){
			
		},
		watch: {
			
		},
		methods: {
			infiniteHandler($state){
				if(this.currentPage> this.maxPage){
					this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
					return;
				}
				
				this.params.currentPage = this.currentPage;
				this.params.pageSize = this.pageSize;
				this.params.status = 1;

				DEVICE_SERVICE.getDeviceList(this.params).then((res)=>{
					const data = res.data;
					if(data && data.length){
						const arr = []
						data.forEach((item) => {
							arr.push({
								label: item.name,
								value: item.id
							})
						})
						if(this.options[0] && 'label' in this.options[0]){
							this.options = this.options.concat(arr);
						}else{
							this.options = arr
						}
						
						this.total = res.recordsTotal;
						this.maxPage = Math.ceil(this.total/this.pageSize);
						this.currentPage++;
						this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
					}else{
						this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
						this.options = []
					}
				})
			},
			visibleChange(isVisible){
				if(isVisible && !this.needInfinite){
					this.needInfinite = true
				}
			},
			remoteMethod(query){
				this.currentPage = 1;
				this.options = [{}] // 这里数组里放空对象才能触发 InfiniteLoading
				this.needInfinite = false;
				this.$nextTick(() => {
			        this.$refs.infiniteLoading && this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
			    });
			    
				this.params.name = query;
				this.needInfinite = true;
			},
			change(value){
				this.$emit('onChange', value)
			}
		},
		components: {
			InfiniteLoading
		}
	}
</script>

<style scoped>
input{
	width: 276px;
}
.infinite-select{
	position: relative;
}
.infinite-panel{
	position: absolute;
	max-height: 40px;
}
</style>