vue3中 子组件有个el-selection 如何让子组件初始化默认展示父组件传的值 然后进行选折的时候搜索框展示选中的值
时间: 2023-07-26 12:15:54 浏览: 60
在Vue 3中,可以使用`v-model`来实现父子组件之间的双向数据绑定。具体的实现步骤如下:
1. 在父组件中,将默认值通过`v-model`传递给子组件:
```html
<template>
<div>
<child-component v-model="selectedValue"></child-component>
</div>
</template>
<script>
export default {
data() {
return {
selectedValue: '默认值'
}
}
}
</script>
```
2. 在子组件中,通过`props`接收父组件传递的默认值,并将其绑定到`el-select`组件的`v-model`上:
```html
<template>
<div>
<el-select v-model="selectedValue" ref="el-select" :remote-method="search" filterable>
<el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value"></el-option>
</el-select>
</div>
</template>
<script>
export default {
props: {
modelValue: String
},
emits: ['update:modelValue'],
data() {
return {
selectedValue: '',
options: [
{
label: '选项1',
value: '1'
},
{
label: '选项2',
value: '2'
}
]
}
},
mounted() {
this.selectedValue = this.modelValue
},
methods: {
search(query) {
// 通过远程搜索接口获取选项数据
// ...
// 搜索完成后,设置选中的值
this.selectedValue = '选中的值'
this.$emit('update:modelValue', this.selectedValue)
}
}
}
</script>
```
在子组件中,通过`props`接收父组件传递的默认值`modelValue`。然后,将`modelValue`绑定到`el-select`组件的`v-model`上,并在`mounted`钩子中将其设置为选中的值。
在选项搜索时,通过调用远程搜索接口获取选项数据,并在搜索完成后,设置`this.selectedValue`来展示选中的值。同时,通过`this.$emit('update:modelValue', this.selectedValue)`来触发`v-model`绑定的更新事件,实现父子组件之间的双向数据绑定。注意,子组件需要通过`emits`选项声明`update:modelValue`事件。
这样,就可以让子组件初始化默认展示父组件传的值,并且在选项搜索时展示选中的值,并且实现了父子组件之间的双向数据绑定。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)