這里打算封裝一個全局el-select組件
MySelect.vue
<template> <el-select v-if="options.length!==0" :value="value" @input="$emit('input',$event)" :placeholder="placeholder" clearable > <el-option v-for="item in options" :key="item[optionVal]" :label="item[label]" :value="item[optionVal]" ></el-option> </el-select> </template> <script> export default { name: "MySelect", props: { options: { type: Array, required: true }, // 綁定value是為了外面也可以傳值改變到里面的值雙向綁定 value: { type: [String, Number,] }, placeholder: { type: String, default: "請選擇~~" }, //optionVal options里面每項對象的值 optionVal: { type: [Number, String], default: "optionVal" }, //lable options里面每項對象的標簽 label: { type: String, default: "lable" } }, data() { return {}; }, methods: {} }; </script> <style lang="scss" scoped> </style>
index.js
import MySelect from "./MySelect"; const compName = MySelect.name; //獲取組件的名字 當做全局組件名字使用 const mySelect = { install(Vue) { Vue.component(compName, MySelect); } }; export default mySelect;
main.js
import MySelect from './components/globalComponents/myselect/index'
Vue.use(MySelect)
使用
<my-select :options='options' option-val='value' label='label' v-model="defaultVal"></my-select>