Vue 二次封装 Element-UI 的 el-select 父子传值
Vue 二次封装 Element-UI Select 组件子组件示例代码父组件调用封装的子组件子组件示例代码<template><div><el-selectv-model="childValue"placeholder="请选择"filterable@change="onChange"><el-optionv-for="item in option
·
Vue 二次封装 Element-UI Select 组件
子组件示例代码
<template>
<div>
<el-select
v-model="childValue"
placeholder="请选择"
filterable
@change="onChange"
>
<el-option
v-for="item in options"
:key="getKey(item.id)"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
<!-- <div>
<slot :user="options"></slot>
</div> -->
</div>
</template>
<script>
export default {
name: "",
props: {
// props是父组件传过来的值
parentValue: null,
url: null,
},
data() {
return {
childValue: this.parentValue,
options: [],
};
},
methods: {
getKey(key) {
return Symbol(key);
},
onChange() {},
getData() {
this.options = [
{ id: "10001", name: "菜狗" },
{ id: "10002", name: "黑骑天使" },
{ id: "10003", name: "六神盾" },
];
},
},
mounted() {
this.getData();
},
watch: {
parentValue(val) {
this.childValue = val;
},
childValue(val) {
this.$emit("input", val); // 实现父子组件间的值传递 this.$emit(事件,值) (这里的input:v-model是一个语法糖,等于:value+@input)
},
},
};
</script>
<style scoped lang='scss'>
</style>
父组件调用封装的子组件
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" width="25%" />
<ChildSelect v-model="selectId" />
<el-button type="primary" @click="getVal">获取选择id</el-button>
<p>{{ selectVal }}</p>
</div>
</template>
<script>
import ChildSelect from "./components/ChildSelect";
export default {
name: "App",
components: {
ChildSelect,
},
data() {
return {
selectId: "",
selectVal: "",
};
},
methods: {
getVal() {
this.selectVal = this.selectId;
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
源码地址
https://codesandbox.io/s/focused-ardinghelli-trzkp?file=/src/App.vue:0-763
更多推荐
已为社区贡献1条内容
所有评论(0)