console
let child=Vue.extend({
template:"#child",
props:{
selections:{
type:Array,
default:[{
label:'test',
value:0
},{
label:'test2',
value:1
}]
}
},
data () {
return {
nowIndex:0
}
},
methods:{
chosenSelection(index) {
this.nowIndex=index;
console.log(this.selections[index])
this.$emit('on-change',this.selections[index])
}
}
})
let parent=new Vue({
el:"#parent",
components:{
'child':child
},
data:{
options:[
{label:'answer1',value:0},
{label:'answer2',value:1},
{label:'answer3',value:2},
{label:'answer4',value:3}
],
answer:{
label:'--',value:0
}
},
methods:{
setAnswer(attr,val){
console.log(attr,val)
this[attr]=val;
}
}
})
<div id="parent">
<p>父元素包含子元素</p>
<child :selections="options" @on-change="setAnswer('answer',$event)"></child>
<p>{{this.answer}}</p>
</div>
<template id="child">
<div class="chooser-component">
<ul class="chooser-list">
<li v-for="(item,index) in selections"
@click="chosenSelection(index)"
:title="item.label"
:class="{active:index==nowIndex}">
{{item.label}}
</li>
</ul>
</div>
</template>
.chooser-component {
position: relative;
display: inline-block;
}
.chooser-list li{
display: inline-block;
border: 1px solid #e3e3e3;
height: 25px;
line-height: 25px;
padding: 0 8px;
margin-right: 5px;
border-radius: 3px;
text-align: center;
cursor: pointer;
}
.chooser-list li.active {
border-color: #4fc08d;
background: #4fc08d;
color: #fff;
}