我有两个vue-选择一个用户和一个地址。我需要获得我选择的ID,这样我就可以将ID发送到我的axios请求,在那里我需要比较用户是否有多个地址,并显示所有这些地址。我知道我需要在父对象上使用v模型,并从子对象发出事件,但我对如何实际获得ID感到困惑。
父组件
<template>
<div>
<search-infinite
class="my-2"
:url="'users'"
:label="'name'"
v-model:selectedUser="selectedUser"
>
</search-infinite>
<search-infinite
:url="'address'"
:label="'address'"
v-model:selectedAddress="selectedAddress"
>
</search-infinite>
</div>
</template>
<script>
import SearchInfinite from "./SearchInfinite";
export default {
name: "Home",
props:{
},
data: () => ({
url: String,
label: String,
selectedUser: "",
selectedAddress:"",
}),
components:{
SearchInfinite
},
methods:{
}
}
</script>
<template>
<v-select
:options="list"
:label="label"
:filterable="false"
@open="onOpen"
@close="onClose"
@search="inputSearch"
class="form-control"
:loading="loading"
>
<template #list-footer>
<li v-show="hasNextPage" ref="load" class="loader">
Loading more options...
</li>
</template>
</v-select>
</template>
<script>
import 'vue-select/dist/vue-select.css';
import _ from "lodash";
export default {
name: 'Search-Infinite',
props:{
url: String,
label: String,
selectedAddress:null,
selectedUser:null,
},
data: () => ({
observer: null,
limit: 10,
search: '',
list: [],
total: 0,
page: 0,
loading: false,
}),
computed: {
hasNextPage() {
return this.list.length < this.total
},
},
mounted() {
this.observer = new IntersectionObserver(this.infiniteScroll)
},
created() {
this.getUsers();
},
methods: {
getUsers(search) {
this.page++;
axios
.get(this.url, {
params: {
search: search,
page: this.page,
}
})
.then((response) => {
this.list = this.list.concat(response.data.data);
this.total = response.data.total;
})
.catch()
.then(() => {
this.loading = false;
})
},
async onOpen() {
await this.$nextTick()
this.observer.observe(this.$refs.load)
},
onClose() {
this.observer.disconnect()
},
async infiniteScroll([{isIntersecting, target}]) {
if (isIntersecting) {
const ul = target.offsetParent
const scrollTop = target.offsetParent.scrollTop
this.limit += 10
this.getUsers();
await this.$nextTick()
ul.scrollTop = scrollTop
}
},
inputSearch: _.debounce( async function (search, loading) {
if (search.length) {
this.list = []
this.loading = true
this.page = 0
this.limit += 10
this.getUsers(search, loading)
await this.$nextTick()
}
}, 500),
},
}
</script>
构造
"data": [
{
"id": 1612,
"name": "Aaliyah Kassulke",
"email": "vgoyette@example.net",
"email_verified_at": null,
"created_at": "2022-05-30T08:45:08.000000Z",
"updated_at": "2022-05-30T08:45:08.000000Z"
},
3条答案
按热度按时间zz2j4svz1#
在一个标准的
select
上,你可以将每个option
上的value
设置为一个嵌套的值,当选择该值时,该值将被返回,例如:在API文档中应该有一个与此相关的prop用于
v-select
,如果没有,您可以添加一个单独的computed
值来返回所选的ID,它将在选择新用户时更新。这是假设您的v-select
在选择时返回用户对象。gt0wga4j2#
如果你只想要id,那么你可以使用reduce函数,如下所示。所以你可以得到v模型中所选选项的直接id。
现在,您可以在parent中侦听event @your-event并获取用户ID。
ffvjumwh3#
也可以使用以下方法:
客户索引更改方法:
这将获取选定项的文本:
事件.目标.选项[事件.目标.选项.选定索引].text
这将获取选项的选定值(id):
event.target.value
我知道,老问题...