vue. js: почему вызывается событие удаления для всех следующих компонентов? - PullRequest
0 голосов
/ 20 января 2020

Пожалуйста, запустите демонстрацию и удалите некоторые элементы с помощью кнопки «удалить меня». Вы увидите, что ввод: число остается старым. Кроме того, число может быть уменьшено как app.$data.numberOfButtons = (app.$data.numberOfButtons*1) -1 - отлично работает с консолью браузера.

Пожалуйста, активируйте эту строку кода сейчас: /* GO TO THIS LINE AND REMOVE COMMENT */ //this.$parent.updateNumberOfButtons(); И теперь нажатие на кнопку «удалить меня» удалит текущий один и все последующие. Почему?!

Vue.component("button-counter", {
        data: function () {
            return {
                dev_name: "button component",
                count: {
                    value: 0,
                    id: this._uid
                }
            }
        },
        methods: {
            updateState() {
                this.count.value++;
            },
            deleteMe() {
                //console.table(this, "button deleteMe()")
                this.$destroy();
            }
        },
        template: '<div><button v-on:click="updateState()">' +
            'Clicked {{ count.value }} times.</button>' +
            ' <button v-on:click="deleteMe()">Remove me</button></div>',
        mounted: function() {
            store.commit("addButton", this.$data.count)
        },
        beforeDestroy:  function () {
            console.log("beforeDestroy()")

            // If we click the remove button the HTML still exist... (only auto removed by input:number)
            if (this.$el.parentNode.parentNode)
                this.$el.parentNode.parentNode.removeChild(this.$el.parentNode);

            //this.$parent.$data.numberOfButtons = (this.$parent.$data.numberOfButtons * 1)- 1;
            //Vue.set(app, this.$parent.$data.numberOfButtons, (this.$parent.$data.numberOfButtons*1) -1);
            //this.$parent.reduceNumberOfButtonsByOne();
            //app.$data.numberOfButtons =  (app.$data.numberOfButtons*1) -1;

            store.commit("removeButton", this.$data.count)
        },
        destroyed: function() {
            console.log("destoyed()");

            // Why this will be fired for all following buttons?!
            /* GO TO THIS LINE AND REMOVE COMMENT */ //this.$parent.updateNumberOfButtons();

            console.log("this: ", this.$data.dev_name);
            console.log("parent: ", this.$parent.$data.dev_name);
        }
    })

    Vue.component("show-count", {
        data: function () {
            return {
                displayValue: store.state.allButtons
            }
        },
        template: '<div><ul><li v-for="(count, index) in displayValue">' +
            'Button {{index+1}}: {{count.value}} (_uid = {{count.id}})</li></ul></div>'
    })

    const store = new Vuex.Store({
        state: {
            allButtons: []
        },
        mutations: {
            addButton(state, value) {
                state.allButtons.push(value)
            },
            removeButton(state, value) {
                var item = state.allButtons.findIndex(obj => obj.id == value.id);
                state.allButtons.splice(item, 1);
            }
        }
    })

    var app = new Vue({
        el: "#test",
        data: {
            dev_name: "main",
            numberOfButtons: 3
        },
        methods: {
            reduceNumberOfButtonsByOne() {
                this.$data.numberOfButtons = (this.$data.numberOfButtons * 1)- 1;
            },
            updateNumberOfButtons() {
                this.$data.numberOfButtons = store.state.allButtons.length;
            }
        }
    })
<div id="test">

    Number of Buttons: <input type="number" v-model="numberOfButtons" min="0">

    <br><hr><br>

    <div v-for="index in numberOfButtons*1">
        <button-counter v-bind:key="index"></button-counter>
    </div>

    <br><hr><br>

    <show-count></show-count>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js"></script>
...