You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js实现单个input编辑选中元素的数组对象title属性

实现思路
  • 父组件统一接管选中状态:移除子组件内部维护的isActive状态,在父组件ItemsList中新增currentSelectedItem变量存储当前选中的元素对象,全局仅维护一个选中状态,保证输入框绑定目标唯一。
  • 输入框双向绑定选中项:通过计算属性将输入框和选中元素的title字段关联,无选中元素时输入框置灰不可编辑,避免空值报错。
  • 父子组件事件通信:子组件点击时触发自定义事件通知父组件,父组件将当前点击的元素设为激活状态,自动同步输入框内容为对应元素的title。
修改后完整代码

ItemsList.vue

<template>
    <input 
        type="text" 
        v-model="editingTitle"
        :disabled="!currentSelectedItem"
        :placeholder="currentSelectedItem ? '编辑选中项标题' : '请先选择要编辑的元素'"
    />
    <div class="items-col">
        <ul class="items-list">
            <Item 
                v-for="item in items" 
                :key="item.title"
                :title="item.title"
                :is-active="currentSelectedItem === item"
                @select="() => currentSelectedItem = item"
            />
        </ul>
    </div>
</template>

<script>
import Item from '@/components/Item.vue'
export default {
    data() {
        return {
            items: [
                { title: 'item 1' },
                { title: 'item 2' },
                { title: 'item 3' },
                { title: 'item 4' },
                { title: 'item 5' },
                { title: 'item 6' }
            ],
            // 存储当前选中的元素
            currentSelectedItem: null
        }
    },
    components: {
        Item
    },
    computed: {
        // 输入框绑定的计算属性,避免空值报错
        editingTitle: {
            get() {
                return this.currentSelectedItem ? this.currentSelectedItem.title : ''
            },
            set(val) {
                if (this.currentSelectedItem) {
                    this.currentSelectedItem.title = val
                }
            }
        }
    }
}
</script>

Item.vue

<template>
    <li class="item" @click="$emit('select')" :class="{ active: isActive }">{{ title }}</li>
</template>

<script>
export default {
    name: 'Item',
    props: {
        title: String,
        // 父组件传入的激活状态
        isActive: Boolean
    }
}
</script>

<style>
    .item.active {
        color: red;
    }
    /* 可选:添加点击手势 */
    .item {
        cursor: pointer;
    }
</style>
可选扩展

如果需要支持多选批量编辑,仅需将currentSelectedItem改为数组类型存储所有选中的元素,输入框提交修改时遍历数组统一更新所有选中元素的title字段即可。

内容的提问来源于stack exchange,提问作者Ioann Sulyma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:15:04