I am trying to implement a checksheet application with Vue, and it looks like this: The tasks to be performed are listed in a excel file.
=====
Perform task A.
Perform task B.
and it goes on...
=====
Then I am thinking about creating a CheckItem.vue
component to be used for each one of the tasks that will look like this:
<template>
<div :class="[isChecked ? 'task-styling' : 'task-styling-checked']">
<div class="task-text">Perform task A.</div>
<img class="task-image" alt="Task 1" src="../assets/img001.png" />
<div class="check-button">
<button
@click="changeColor"
type="submit"
class="check-buttom"
>
Check
</button>
</div>
</div>
</template>
What I would like to accomplish:
Use the same "CheckItem.vue" component above to all tasks in the list, but with the "task-text" and "task-image" fields filled with their proper contents.
At the moment, I do not mind hard coding that fields contents manually (eventually, would like to do it in a smarter way). I just need to know how I can use the same component with different data inserted.
Try like following snippet, you can make dynamic components by looping thru your data object with v-for and by passing props
const App = {
data() {
return {
tasks: [{id: 1, text: 'aaa', img: 'https://picsum.photos/30/29'}, {id: 2, text: 'bbb', img: 'https://picsum.photos/30/30'}, {id: 3, text: 'ccc', img: 'https://picsum.photos/30/31'}]
}
}
}
const app = Vue.createApp(App)
app.component('CheckItem', {
template: `
<div :class="isChecked ? 'task-styling-checked' : 'task-styling'" class="task">
<div class="task-text">{{ task.text }}</div>
<img class="task-image" alt="Task 1" :src="task.img" />
<div class="check-button">
<button
@click="changeColor"
type="submit"
class="check-buttom"
>
Check
</button>
</div>
</div>
`,
props: ['task'], //👈
data() {
return {
isChecked: false
}
},
methods: {
changeColor() {
this.isChecked = !this.isChecked
}
}
})
app.mount("#demo");
.task-styling {
background: skyblue;
}
.task-styling-checked {
background: peru;
}
.task {
padding: 1em;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="demo">
<div v-for="item in tasks" :key="item.id"> <!-- 👈 -->
<check-item :task="item"></check-item>
</div>
</div>