Vue Element Select 選擇器

Element Select 選擇器  

本示例以 Vue Element Admin 項目爲基礎,介紹 Element Select 選擇器【遠程搜索

1、/src/views/select.vue

<template>
  <div class="app-container">
    <el-select
      v-model="roleSelect.value"
      multiple
      filterable
      remote
      reserve-keyword
      placeholder="請輸入關鍵詞"
      :remote-method="remoteMethod"
      :loading="roleSelect.loading"
    >
      <el-option v-for="item in roleSelect.options" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
  </div>
</template>

<script>
import { getRoles } from "@/api/select";

export default {
  data() {
    return {
      roleSelect: {
        options: [],
        value: [],
        list: [],
        loading: false
      },
      listQuery: {
        page: 1,
        per_page: 50
      }
    };
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        this.roleSelect.loading = true;
        setTimeout(() => {
          this.roleSelect.loading = false;
          this.roleSelect.options = this.roleSelect.list.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.roleSelect.options = [];
      }
    },
    async getRoleList() {
      getRoles(this.listQuery)
        .then(res => {
          let mapData = res.data.items.map(item => {
            return { value: item.role_code, label: item.role_name };
          });
          this.roleSelect.value = res.data.items[0].role_code; // 設置第一個值爲選中狀態
          this.roleSelect.options = mapData;
          this.roleSelect.list = mapData;
        })
        .catch(err => {
          console.error(err);
        });
    }
  }
};
</script>

2、/src/api/select.js

import request from '@/utils/request'

export function getRoles(query) {
  return request({
    url: '/v1/roles',
    method: 'get',
    params: query
  })
}

3、服務端 API 接口返回 json 數據

{
  "data": {
    "items": [
      { "role_code": 1,"role_name": "超級管理員" },
      { "role_code": 2,"role_name": "管理員" },
      { "role_code": 3,"role_name": "普通用戶" },
      { "role_code": 4,"role_name": "鑽石" },
      { "role_code": 5,"role_name": "金牌" },
      { "role_code": 6,"role_name": "銀牌" }
    ],
    "total": 6,
    "page_count": 1
  },
  "code": "200",
  "msg": null
}

*
*
*

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章