Vue 3 select 组件如何将 2 个属性绑定到 2 个 v-model
Vue 3 select component how to bind 2 attributes to 2 v-model
所以假设我有一个数据 - news: {id:3, name:"book", author:'author'}
。
select 和 options: {id: 1, book: "book1"}, {id: 2, book: "book2"}
.
现在我想用 news.id 和 news.book v-bind 选项
有没有办法做到这一点或为此准备好的组件?
<select v-model="selected">
<option v-for="option in options" :value="option.id">
{{ option.name}}
</option>
</select>
data() {
return {
selected: 1,
options: [
{ name: 'book1', id: 1 },
{ name: 'book2', id: 2 },
{ name: 'book3', id: 3 }
]
}
所以最后我做了这个:
<select1
:selected="{ id: book.id, name: book.name }"
v-model:id="book.id"
v-model:name="book.name"
urldata="url/to/get/options"
></select1>
我的组件是这样的:
<template>
<div>
<select v-model="selected" @change="change" class="form-select">
<option v-for="option in options" :value="option">
{{ option.name }}
</option>
</select>
</div>
</template>
export default {
name: "select1",
emits: ["update:selected", "update:id", "update:name"],
props: {
selected: Object,
urldata: String,
},
data: function () {
return {
options: [],
};
},
mounted() {
this.GetListData();
},
methods: {
GetListData() {
if (this.urldata !== "") {
axios
.get(`${this.urldata}`)
.then((response) => (this.options = response.data.results));
}
},
change(event) {
console.log(this.selected);
this.$emit("update:selected", this.selected);
this.$emit("update:id", this.selected.id);
this.$emit("update:name", this.selected.name);
},
},
};
所以假设我有一个数据 - news: {id:3, name:"book", author:'author'}
。
select 和 options: {id: 1, book: "book1"}, {id: 2, book: "book2"}
.
现在我想用 news.id 和 news.book v-bind 选项 有没有办法做到这一点或为此准备好的组件?
<select v-model="selected">
<option v-for="option in options" :value="option.id">
{{ option.name}}
</option>
</select>
data() {
return {
selected: 1,
options: [
{ name: 'book1', id: 1 },
{ name: 'book2', id: 2 },
{ name: 'book3', id: 3 }
]
}
所以最后我做了这个:
<select1
:selected="{ id: book.id, name: book.name }"
v-model:id="book.id"
v-model:name="book.name"
urldata="url/to/get/options"
></select1>
我的组件是这样的:
<template>
<div>
<select v-model="selected" @change="change" class="form-select">
<option v-for="option in options" :value="option">
{{ option.name }}
</option>
</select>
</div>
</template>
export default {
name: "select1",
emits: ["update:selected", "update:id", "update:name"],
props: {
selected: Object,
urldata: String,
},
data: function () {
return {
options: [],
};
},
mounted() {
this.GetListData();
},
methods: {
GetListData() {
if (this.urldata !== "") {
axios
.get(`${this.urldata}`)
.then((response) => (this.options = response.data.results));
}
},
change(event) {
console.log(this.selected);
this.$emit("update:selected", this.selected);
this.$emit("update:id", this.selected.id);
this.$emit("update:name", this.selected.name);
},
},
};