<template>
<div>
<h1>My To Do List</h1>
</br>
<!--displays list -->
<ul>
<li v-for="item in listItems">{{ item }}</li>
</ul>
</div>
</template><script>
export default {
name: 'list',
data () {
return {
listItems: ['buy food', 'play games', 'sleep'],
}
}
}
</script>
在组件中,列表项存储在组件数据中的数组(listItems)中。然后可以在模板中访问该数据,并在foreach循环中循环(v-for),并显示在页面上。
为了使我们的列表看起来更有趣,我们可以创建一个新的路径来显示我们的组件。进入src/router/index.js并添加路由,你的代码应该是这样的:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import List from '@/components/List'Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},
{
path: '/to-do',
name: 'ToDo',
component: List
},
]})
现在,如果您导航到localhost:8080/#/to-do,您将在浏览器中看到您的列表效果!
首先我们要测试数据是否正确显示。在 test/unit/specs 下创建一个新的文件List.spec.js并放上如下代码:
import List from '@/components/List';
import Vue from 'vue';describe('List.vue', () => {
it('displays items from the list', () => {
// our test goes here
})
})
在这个文件中,我们描述List.vue组件,我们有一个单独的空测试,它将检查它(组件)是否从列表中显示项目。这是Mocha测试的基本文件结构。
在我们的测试中,我们首先需要设置Vue组件。复制下面的代码,并将其放在注释“our test goes here”的位置:
// build component
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();
我们扩展Vue然后安装我们的组件。安装组件很重要,因为这是在我们的模板中呈现HTML。这实际上意味着HTML被构建,并且我们的模板中的变量(例如{{item}})被填满数据,使得我们可以访问HTML(通过$el)。
随着我们的组件准备好,我们可以写第一个断言。在这个例子中,我们使用了’expect’风格,由Chai断言库提供,以及’should’和’assert’。 安装组件后放置以下代码:
// assert that component text contains items from the list
expect(ListComponent.$el.textContent).to.contain('play games');










