I’m trying to use Vue for the first time and I want to render HTML for each item in an array. Specifically, whenever a new item is added to the array, I would like the HTML to be updated accordingly.
Here’s what I’ve tried so far:
document.addEventListener('DOMContentLoaded', () => {
const app = Vue.createApp({
data() {
return {
messages: []
};
},
methods: {
addMessage(message) {
this.messages.push(message);
}
},
template: `
<div class="list-group">
<div v-for="(message, index) in messages" :key="index" class="list-group-item">
<div class="d-flex">
<div class="p-2">
<i class="fa-solid fa-user fa-2xl text-primary"></i>
{{ message.role === 'user' ? '<i class="fa-solid fa-user fa-2xl text-primary"></i>' : '<i class="fa fa-robot fa-2xl text-primary"></i>' }}
</div>
<div class="p-2 flex-grow-1">{{ message.text }} <button type="button" class="copy-button">Copy</button></div>
</div>
</div>
</div>
`
});
app.mount('#app');
for (let i = 0; i < 10; i++) {
app.addMessage({
role: 'user',
text: 'message #' + i
});
}
});
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app"></div>
But keep getting an error in the console
Uncaught TypeError: app.addMessage is not a function
How can I resolve this issue?
Additionally, I want to add buttons to my template. After the HTML is rendered and added to the DOM, I would like to attach event listeners to these buttons. For example, for any button with the class copy-button
, I want to add an event listener so that when the user clicks any button with that class, it logs “Hello” to the console.
How can I add event listeners to dynamically added elements after they are inserted into the DOM?