做了两个子组件,原理基本一样,一个是使用原生的select元素,一个是使用element-ui的el-select组件。并实现了子组件的value属性值到父组件的双向绑定,以及一些属性值的单向绑定。
<!DOCTYPE html>
<!--
自定义组件学习,wallimn,20190308
-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>自定义组件学习</title>
<!-- 引入组件样式 -->
<link rel="stylesheet" href="../res/lib/element-ui.v2.4.9/theme-chalk/index.css">
</head>
<body class="main">
<div id="app">
<div>自定义组件示例(element-ui组件封装)1:<agent-select1 :options="agents" v-model="selectAgent1" placeholder="请选择代理商"></agent-select1>选择代理商:{{selectAgent1}}</div>
<div>自定义组件示例(原生组件封装)2:<agent-select2 :options="agents" v-model="selectAgent2" placeholder="请选择代理商"></agent-select2>选择代理商:{{selectAgent2}}</div>
</div>
<script type="text/javascript" src="../res/lib/vue.js"></script>
<script src="../res/lib/element-ui.v2.4.9/index.js"></script>
<!--agent-select1===定义开始===-->
<!--组件模板-->
<script type="text/x-template" id="t-agent-select1">
<el-select :value="localValue" @input="updateVal($event)" :placeholder="placeholder" clearable>
<el-option
v-for="v in options"
:key="v.value"
:label="v.label"
:value="v.value">
</el-option>
</el-select>
</script>
<!--组件定义-->
<script type="text/javascript">
Vue.component("agent-select1",{
template:"#t-agent-select1",
props:["value","options","placeholder"],//通过props实现数据到子组件的传递
data: function(){
return {
localValue:""
};
},
methods :{
updateVal: function(val){
this.$emit("input",val);//通过事件实现组件属性到父组件的传递
this.localValue=val;
}
}
});
</script>
<!--agent-select1===定义结束===-->
<!--agent-select2===定义开始===-->
<script type="text/x-template" id="t-agent-select2">
<select v-model="localValue" @input="updateVal($event.target.value)" :placeholder="placeholder">
<option v-for="v in options" :key="v.value" :value="v.value">{{v.label}}</option>
</select>
</script>
<script type="text/javascript">
Vue.component("agent-select2",{
template:"#t-agent-select2",
props:["options","value","placeholder"],//通过props实现数据到子组件的传递
data: function(){
return {localValue:null}
},
methods: {
updateVal: function(val){
this.localValue=val;
this.$emit("input",val);//通过事件实现组件属性到父组件的传递
}
}
});
</script>
<!--agent-select2===定义结束===-->
<script type="text/javascript">
// Vue实例化
new Vue({
el:"#app",
data: {
selectAgent1:"",//组件1选中值
selectAgent2:"",//组件2选中值
agents:[
{value:"",label:""},
{value:1,label:"代理商01"},
{value:2,label:"代理商02"},
{value:3,label:"代理商03"},
{value:4,label:"代理商04"}
]//代理商列表
}
});
</script>
</body>
</html>