【问题标题】:Can I pre select a value in an PrimeVue Dropdown component?我可以在 PrimeVue 下拉组件中预先选择一个值吗?
【发布时间】:2021-08-27 07:56:16
【问题描述】:

案例:我在Vue.js 项目中使用PrimeVue。在这种情况下,我有一个下拉列表,作为来自PrimeVue 的组件,它使用对象数组。下拉组件如下所示:

<template #position>
    <Dropdown
        class="multiselect-fullsize"
        v-model="selectedFilter[index].pos"
        :options="filterPositions"
        optionLabel="name"
        placeholder="Position" />
    </template>

这个下拉组件有一个:options 属性,它引用了以下数组:

filterPositions: [
    {"name": "0", "value": "0"},
    {"name": "1", "value": "1"},
    {"name": "2", "value": "2"},
    {"name": "3", "value": "3"},
    {"name": "4", "value": "4"},
    {"name": "5", "value": "5"},
    {"name": "6", "value": "6"},
    {"name": "7", "value": "7"},
    {"name": "8", "value": "8"}
  ]

问题:有没有办法在 PrimeVue 的下拉列表中指定预选项目?

编辑:根据documentation,没有定义预选项目的属性。所以也许,如果有解决方案,它可能只是JavaScript

【问题讨论】:

  • 如果无法进行预选择,我已经在我的应用程序的后期找到了一种解决方法。但这并不能回答我的问题。
  • @AlexandreElshobokshy 我很快就会试试这个。谢谢!
  • 那你有没有试过,加个name属性?
  • @AlexandreElshobokshy 我尝试了解决方案,但没有奏效。

标签: javascript vue.js primevue


【解决方案1】:

答案是:是的! Dropdown | PrimeVue 文档中的描述有点令人困惑,至少对我来说是这样。问题是,提供v-model 是不够的,就像我对v-model="selectedFilter[index].pos" 所做的那样,我还必须定义optionValue,在我的情况下是optionValue="value",因为filterPositions 中的值具有密钥value.

看起来,如果设置了此项,PrimeVue 的下拉菜单能够检查 v-model 是否与 optionValue 匹配。如果不是,v-model 将与整个 filterPositions 项目进行比较。例如:

没有optionValue="value"

{"name": "4", "value": "4"} === 4

optionValue="value":

4 === 4

因此,在这种情况下,我的 Dropdown 组件必须如下所示:

<Dropdown
    class="multiselect-fullsize"
    v-model="selectedFilter[index].pos"
    :options="filterPositions"
    optionLabel="name"
    optionValue="value"
    placeholder="Position"
/>

【讨论】:

    【解决方案2】:
    selectedFilter[index].pos = {"name": "4", "value": "4"}
    

    【讨论】:

    • 见“Explaining entirely code-based answers”。虽然这在技术上可能是正确的,但它并不能解释为什么它可以解决问题或应该是选择的答案。除了帮助解决问题,我们还应该进行教育。
    【解决方案3】:

    只需将占位符值设置为预选值

    <Dropdown
    class="multiselect-fullsize"
    v-model="selectedFilter"
    :options="filterPositions"
    optionLabel="name"
    optionValue="value"
    :placeholder="selectedFilter.value"
    />
    

    【讨论】:

    • 嘿,这正是我 2 周前的回答。
    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2010-12-06
    • 2012-01-17
    • 2012-04-03
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多