0
点赞
收藏
分享

微信扫一扫

el-tree-select 调用接口搜索能力封装

<template>

  <div class="remote-tree-select">

    <el-tree-select

      v-model="selectedValue"

      :data="treeData"

      :props="treeProps"

      :remote="true"

      :remote-method="handleRemoteSearch"

      :loading="loading"

      placeholder="输入关键词搜索"

      style="width: 300px"

      clearable

      check-on-click-node

    ></el-tree-select>

  </div>

</template><script>

import axios from 'axios';export default {

  data() {

    return {

      selectedValue: null,

      treeData: [],

      loading: false,

      treeProps: {

        children: 'children',

        label: 'name',

        value: 'id'

      },

      // 防抖计时器

      searchTimer: null

    };

  },

  methods: {

    /**

     * 处理远程搜索

     * @param {string} query - 搜索关键词

     */

    handleRemoteSearch(query) {

      // 清除之前的计时器

      if (this.searchTimer) {

        clearTimeout(this.searchTimer);

      }      // 防抖处理,避免频繁调用接口

      this.searchTimer = setTimeout(async () => {

        // 如果搜索词为空,可根据需求决定是否加载全部数据或清空

        if (!query) {

          this.treeData = [];

          return;

        }        try {

          this.loading = true;

          // 调用后端接口搜索

          const response = await axios.get('/api/tree/search', {

            params: {

              keyword: query,

              // 可添加其他参数,如层级深度等

              depth: 2

            }

          });          // 假设接口返回格式为 { code: 200, data: [...] }

          if (response.data.code === 200) {

            this.treeData = response.data.data;

          } else {

            this.$message.error('搜索失败,请重试');

            this.treeData = [];

          }

        } catch (error) {

          console.error('搜索接口调用失败:', error);

          this.$message.error('网络错误,搜索失败');

          this.treeData = [];

        } finally {

          this.loading = false;

        }

      }, 300); // 300ms防抖延迟

    }

  },

  beforeDestroy() {

    // 清除计时器

    if (this.searchTimer) {

      clearTimeout(this.searchTimer);

    }

  }

};

</script><style scoped>

.remote-tree-select {

  padding: 20px;

}

</style>

举报

相关推荐

0 条评论