The script
<script>
import { ref, reactive } from 'vue';
export default {
data() {
const todo = ref('');
const list = reactive([]);
return { todo, list };
},
components: {
navbar,
},
methods: {
render() {
console.log(this.list.length);
return this.list
.map((item, index) => {
return `<div class="task"><p>${item.todo}</p><button @click="list.splice(index, 1)">del</button></div>`;
})
.join('');
},
},
};
</script>
The Html
<div class="list-container">
<div class="task-container" v-if="list.length" v-html="render()"></div>
<div class="task-container" v-else>nothing in here</div>
</div>
The data structure in the list array
{todo: 'text', checked: false},
...
I’m building a todo app so I’m trying to remove the selected todo from the list array without using v-for or emit but the @click directive is being read as a string. How can I get it to work?
I’d like to know how to do it this way specifically so that’s why I don’t want to use the other methods mentioned above.
2
Answers
This is not going to work.
https://vuejs.org/api/built-in-directives.html#v-html
i don’t think this is best the way to handle or work and learn vue but for your information what can be done is create a method remove task and add a mounted lifecycle hook to assign the removeTask method to the window object. This way, it can be accessed from within the HTML string.
By the way {{item.todo}} will be undefined as per as your logic do change it and everything will work as you wanted.