首页 > 解决方案 > 如何使用 VueJS 列出多个组件?

问题描述

我已经用 vue.js 创建了待办事项列表,我想每隔 4 个列表项添加一些图像,所以我认为使用 v-html 和数组,其中包含与文本绑定的元素以及带有元素的图像,对吗?

例如)

var arr = [<div v-bind:foo><div>, 
<div v-bind:foo><div>, 
<div v-bind:foo><div>, 
<img src="..."/>] 

这是待办事项列表(使用 v-html 之前)

https://codepen.io/Retzudo/pen/WwEMQZ

标签: vue.jsvuejs2

解决方案


在您的列表循环中执行以下操作

<li v-for="todo in todos | orderBy 'done'">
            <del v-if="todo.done">
                {{ todo.text }}
            </del>
            <template v-else>
                {{ todo.text }}
            </template>
            <img v-bind:src="todo.image" alt="test" v-if="todo.image"/>
      <a href="" @click.prevent="todo.done = !todo.done">✓&lt;/a>
</li>

并在列表的长度中添加一个观察者,如果它是第四个,则将图像添加到最后一个待办事项:

(function () {
    new Vue({
        el: '#todo-list',
        data: {
            todos: [
                {
                    text: 'Do stuff',
                    done: false,
                    image: ''
                },
                {
                    text: 'Done thing',
                    done: true,
                    image: ''
                },
                {
                    text: 'Other stuff',
                    done: false,
                    image: ''
                }
            ]
        },
        watch: {
            todos: function (list) {
        if(list.length%4 == 0) {
        this.todos[list.length-1].image = 'https://www.w3schools.com/w3css/img_lights.jpg';
    }
}
        },
        methods: {
            new: function () {
                this.todos.push({
                    text: this.todoText,
                    done: false,
                    image: ''
                });
                this.todoText = '';
            }
        }
    });
}());

推荐阅读