【问题标题】:Vue updating components at the same time after pushVue推送后同时更新组件
【发布时间】:2020-12-13 01:17:29
【问题描述】:

我正在Vue中构建一个表单

我有一个如下所示的组件:

<template>
    <transition name="preview-pane">
    <label>{{ option.group }}</label>
    <input type="text" class="form-control"
         :name="`group_name[${index}]`"
         v-on:input="option.group = $event.target.value"
         :value="option.group">
               
    <a ref="#" class="btn btn-primary float-right" @click="$emit('copy')" role="button">{{ __('Copy') }} </a>
    </transition>
</template>

<script>
    export default {
        props: {
            option: {
                group: ''
            },
            index: {}
        }
    }
</script>

我的Vue 实例如下:

var products = new Vue({
    el: '#products',
    data: {
        options: []
    },
    methods: {
        add() {
            this.options.push({
                group: ''
            })
        },
        copy(index) {
            this.options.push(this.options[index])
        }
    }
})

最后我的 html 如下所示

<product-option 
   v-for="(option, index) in options" 
   :key="index"
   :option="option"
   :index="index"
   @copy="copy(index)">
</product-option>

我有一个按钮,它基本上采用其中一个选项并再次按下它(vue 实例上的复制方法)。当我运行时一切似乎都很好,但是当我更改输入时,它会更新所有已复制组件的道具。

如何让 vue 理解每个组件应该单独工作?

【问题讨论】:

  • 你不是用this.options.push(this.options[index])复制的
  • @Estradiaz 是的,它有效,你是什么意思?
  • 试试let opts = [{value: 1}]; opts.push(opts[0]); opts[0].value = 2; console.log(opts[1].value) //2
  • 还是达不到我的要求

标签: vue.js vue-component


【解决方案1】:

如果有人遇到同样的问题,我会这样解决:

copy(index) {
    var object = this.options[index]
    var newObject = {}
    for (const property in object) {
        newObject[property] = object[property]
    }
    this.options.push(newObject)
}

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2020-02-16
    • 2020-07-26
    • 2021-05-02
    • 2021-09-12
    • 1970-01-01
    • 2018-04-13
    • 2022-08-23
    • 2021-08-21
    相关资源
    最近更新 更多