【问题标题】:How do have unique variables for each dynamically created buttons/text fields?如何为每个动态创建的按钮/文本字段设置唯一变量?
【发布时间】:2022-11-29 12:23:59
【问题描述】:

我正在尝试为页面上的每个项目创建按钮和 vue 元素输入。我正在遍历这些项目并使用 v-for 呈现它们,所以我决定扩展它并为其余两个做同样的事情。我遇到的问题是我需要将textInputdisplayTextbox 绑定到每个,但我不确定如何实现。

目前 el-inputs 中的所有输入文本都绑定到同一个变量,单击以显示输入将一次显示所有输入。

<template>
    <div class="container">
        <div v-for="(item, index) in items" :key="index">
            <icon @click="showTextbox"/>
            <el-input v-if="displayTextbox" v-model="textInput" />
            <el-button v-if="displayTextbox" type="primary" @click="confirm" />
            <ItemDisplay :data-id="item.id" />
        </div>
    </div>
</template>

<script>
import ItemDisplay from '@/components/ItemDisplay';

export default {
    name: 'ItemList',

    components: {
        ItemDisplay,
    },

    props: {
        items: {
            type: Array,
            required: true,
        },
    }

    data() {
        displayTextbox = false,
        textInput = '',
    },

    methods: {
        confirm() {
            // todo send request here
            this.displayTextbox = false;
        },

        showTextbox() {
            this.displayTextbox = true;
        }
    }
}
</script>

【问题讨论】:

  • 您可以为模型使用 displayTextbox 数组吗?

标签: vue.js


【解决方案1】:

[假设你使用的是 Vue2]
如果你想与多个displayTextbox + textInput状态交互,你需要有一组对象this example 中的每个键都绑定了一个特定的键。
截至目前,您对它们只有 1 个状态,这意味着如您所见:您可以将其切换为全部或仅无。

您需要像我上面的示例中那样使用一个对象重构它,以允许在每个状态上单独进行个案迭代。

PS::key="index" 不是一个有效的解决方案,你永远不应该将 v-forindex 用作 explained here
PS2:模板中的组件命名请关注the conventions


另外,我不确定你打算将你的组件深入到什么程度,因为我们不知道&lt;ItemDisplay :data-id="item.id" /&gt; 的内部结构。
但是,如果您还想为每个输入管理 the labels,您可以使用 nanoid 来实现,这样您就可以为每个输入设置唯一的 UUID,这非常有用。

【讨论】:

    【解决方案2】:

    使用数组来存储值,如下所示:

    <template>
        <div v-for="(item, index) in items" :key="index">
            <el-input v-model="textInputs[index]" />
        </div>
    <template>
    
    <script>
    export default {
        props: {
            items: {
                type: Array,
                required: true,
            },
        },
        data() {
            textInputs: []
        }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2021-11-15
      相关资源
      最近更新 更多