【问题标题】:Vue 3 select component how to bind 2 attributes to 2 v-modelVue 3选择组件如何将2个属性绑定到2个v-model
【发布时间】:2021-06-29 09:50:28
【问题描述】:

假设我有一个数据 - news: {id:3, name:"book", author:'author'}。 并选择options: {id: 1, book: "book1"}, {id: 2, book: "book2"}

现在我想用 news.id 和 news.book 绑定选项 有没有办法这样做或为此准备好组件?

【问题讨论】:

    标签: drop-down-menu vue-component vuejs3 vue-select


    【解决方案1】:
    <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 }
          ]
        }
    

    【讨论】:

    • 这就是你可以做一个对象数组的方法。也许我问了一个不准确的问题。但是我可以将此 selected.name 和 selected.id 绑定到我的模型新闻,以便它是反应性的。所以我不需要在操作结束时选择地址来更改我的数据。
    • 我不确定你的意思。您可以使用 this.options.find(option => option.id == this.selected).name 访问选定的选项名称。您应该只在一处拥有“真实”或“真实”数据。
    【解决方案2】:

    所以最后我做了这个:

    <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);
        },
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 1970-01-01
      • 2020-07-15
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多