I’m attempting to write a todo app as my first ever vue.js project. It seems it’s not showing my items in the TodoItem component — inside the h3 tag.
I’ve double-checked everything but I just can’t see anything wrong. Why are my items not appearing?
App.vue:
<template>
<div id=”app”>
<Todos v-bind:todos=”todos” message=”Here are the daily tasks”/>
</div>
</template>
<script>
import Todos from ‘./components/Todos.vue’
export default {
name: ‘app’,
components: {
Todos
},
data: {
todos: [
{
id: 1,
title: “Todo one”,
completed: false,
},
{
id: 2,
title: “Todo two”,
completed: false,
},
{
id: 3,
title: “Todo three”,
completed: true,
}
]
}
}
</script>
<style>
#app {
font-family: ‘Avenir’, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Todos:
<template>
<div class=”hello”>
<h1>{ message }</h1>
<div v-bind:key=”todo.id” v-for=”todo in todos”>
<TodoItem v-bind:todo=”todo” />
</div>
</div>
</template>
<script>
import TodoItem from ‘../components/TodoItem.vue’
export default {
name: “Landing”,
components: {
TodoItem
},
props: [“message”, “todos”],
data: {
}
};
</script>
<!– Add “scoped” attribute to limit CSS to this component only –>
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
TodoItem:
<template>
<div class=”todo-item”>
<h3>ITEM: test</h3>
</div>
</template>
<script>
export default {
name: “TodoItem”,
props: [“todo”],
data: {
}
};
</script>
<!– Add “scoped” attribute to limit CSS to this component only –>
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
Solution :
data must be a function for a component. the code renders the items if you make the following changes:
export default {
name: ‘App’,
components: {
Todos,
},
data() {
return {
todos: [
{
id: 1,
title: ‘Todo one’,
completed: false,
},
{
id: 2,
title: ‘Todo two’,
completed: false,
},
{
id: 3,
title: ‘Todo three’,
completed: true,
},
],
};
},
};
I highly recommend integrating eslint along with eslint-plugin-vue.js into the editor to avoid these kinds of common errors.
Solution 2:
As previously stated, data in a vue.js component must be a function.
Here’s a working version to help you out:
https://codesandbox.io/s/vue-template-ds5up?fontsize=14