<template>
<el-select v-model="curFruit" @change="change">
<el-option
v-for="(item,index) in fruits"
:key="index"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</template>
<script>
export default {
name: 'my-fruits',
data() {
return{
fruits: [
{label: '苹果', value: 'apple'},
{label: '香蕉', value: 'banana'},
{label: '西瓜', value: 'watermelon'}
]
},
props: {
curFruit: {
type: [String,Number],
default: ''
}
}
},
methods: {
change(val) {
this.$emit('change',val)
}
}
}
</script>
<template>
<fruit :curFruit="fruit" @change="change"></fruit>
</template>
<script>
import fruit from "./components/fruit"
export default {
name: 'index',
components:{
fruit
},
data() {
return{
fruit: ''
}
},
methods: {
change(val) {
console.log('子组件传递的水果value-->',val);
// 操作逻辑...
}
}
}
</script>
在vue 2.2.0之后新增了model属性,方便组件之间传递值
通过接收curFruit(有时候让下拉框自动选择url中携带的参数),通过change事件抛出选中的值
子组件
<template>
<el-select
v-model="curFruit"
@change="$emit('change',$event)"
>
<el-option
v-for="(item,index) in fruits"
:key="index"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</template>
<script>
export default {
name: 'my-fruits',
model: {
prop: 'curFruit',
event: 'change'
},
data() {
return{
fruits: [
{label: '苹果', value: 'apple'},
{label: '香蕉', value: 'banana'},
{label: '西瓜', value: 'watermelon'}
]
}
}
}
</script>
父组件
通过v-model绑定curFruit,将值传递给子组件的prop(curFruit),同时接收子组件的event(change)事件抛出的值
<template>
<fruit v-model="curFruit"></fruit>
</template>
<script>
import fruit from "./components/fruit"
export default {
name: 'index',
components:{
fruit
},
data() {
return{
curFruit: '',
params: {
fruit: ''
}
}
},
watch: {
curFruit: {
handler(newVal,oldVal) {
// 监听curFruit的值给参数对象,发请求
this.params.fruit = newVal
}
}
}
}
</script>
按时下班是程序员毕生追求,加油!!