在渲染之前添加数据后如何获得子组件?

时间:2019-05-20 04:54:01

标签: javascript vue.js vuejs2 vue-component

我想在添加数据后设置子组件的一些道具,但是我该怎么办呢?

对于下面的示例,我想选择在方法additem()中添加的项目,如何在Vue中实现它?

Vue.component('list-item', {
    props: ['text'],
    data() {
        return {
            selected: false,
        }
    },
    methods: {
        click() {
            this.selected = true;
        }
    },
    template: `
        <li v-bind:class="{ selected : selected }" v-on:click="click">{{text}}</li>
    `
});

var idx = 0;
Vue.component('list', {
    data() {
        return {
            list: [],
        }
    },
    methods: {
        additem() {
            this.list.push("li " + idx++);
        }
    },
    template: `
        <div>
            <button v-on:click="additem">Add</button>
            <ul>
                <list-item v-for="item in list" v-bind:text="item"></list-item>
            </ul>
        </div>
    `
});

var demo = new Vue({
    el: "#demo"
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <style>
        li.selected {
            color: red;
        }
    </style>
    <list id="demo"></list>
    <script src="./stackoverflow.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

不能。重新渲染后,列表项将丢失其数据。

您必须将所选属性添加到列表组件中的item对象。

Vue.component('list-item', {
    props: ['item'],
    methods: {
        click() {
            this.$emit('clicked');
        }
    },
    template: `
        <li :class="{ selected : item.selected }" @click="click">{{ item.text }}</li>
    `
});

var idx = 0;
Vue.component('list', {
    data() {
        return {
            list: [],
        }
    },
    methods: {
        additem() {
            this.list.push({
                text: "li " + idx++,
                selected: false,
            });
        },
        onClick(item) {
            item.selected = !item.selected;
        },
    },
    template: `
        <div>
            <button v-on:click="additem">Add</button>
            <ul>
                <list-item 
                    v-for="item in list"
                    :item="item"
                    @clicked="onClick(item)"
                    :key="item.text">
                </list-item>
            </ul>
        </div>
    `
});

var demo = new Vue({
    el: "#demo"
});