Implementing event handlers with 'v-on' on dynamically inserted content using 'v-html' in Vue

Can Vue allow for the addition of v-on events on strings included in v-html? In this scenario, clicking the 'Maggie' link doesn't produce any action. It appears that it's not recognized by Vue.

Is there an alternative method to achieve this? I am currently using Vue.js version 2.1.3

Javascript

window.onload = function() {
    new Vue({
        el: '#app',
        data: {
            users: ['Homer', 'Marge', 'Bart', 'Lisa', '<a href="#" v-on:click="click_user">Maggie</a>']
        },
        methods: {
            click_user: function() {
                console.log('Click user')
            },
        }
    })
}

HTML

<div id="app">
    <div v-for="user in users" v-html="user"></div><br>
    <a href="#" v-on:click="click_user">This works.</a>
</div>

Answer №1

According to the information provided in the vue documentation:

The innerHTML of an element can be updated using the v-html directive. It is important to note that the content will be inserted as plain HTML and not compiled as Vue templates. If there is a need to create templates using v-html, it is recommended to reconsider the approach by utilizing components instead.

It should be noted that v-on will not function within v-html because it relies on Vue for functionality.


A Possible Resolution for Your Specific Issue

To conditionally display a link by using v-if, or else render plain text.

new Vue({
  el: '#app',
  data: {
    users: [
      { name: 'Homer', clickable: false },
      { name: 'Marge', clickable: false },
      { name: 'Bart', clickable: false },
      { name: 'Lisa', clickable: false },
      { name: 'Maggie', clickable: true },
    ]
  },
  methods: {
    click_user: function() {
      console.log('Click user')
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.0/vue.js"></script>

<div id="app">
  <div v-for="user in users">
    <div v-if="!user.clickable">{{user.name}}</div>
    <a v-if="user.clickable" href="#" v-on:click="click_user">{{user.name}}</a>
  </div>
</div>

Answer №2

When using v-html to render

<a href="#" v-on:click="click_user">Maggie</a>
, the click event will not be bound. More information can be found in the official documentation. The v-on:click will simply render as an attribute.

It's recommended to keep a simple array of data and avoid using v-html. Instead, use either text or index with if (for one or two conditions) or switch (for multiple conditions) to trigger events.

window.onload = function() {
    new Vue({
        el: '#app',
        data: {
            users: ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
        },
        methods: {
            click_user: function(text) {
              if(text=='Maggie') console.log('Click user')
            }
        }
    })
}

<div id="app">
   <div v-for="user in users" v-on:click="click_user(user)">{{user.name}}</div><br>    
</div>

Alternatively,

window.onload = function( ) {
  new Vue({
      el: '#app',
      data: {
          users: ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
      },
      methods: {
        click_user: function(index) {
          if(index==4) console.log('Click user')
        }
      }
   })
}

<div id="app">
   <div v-for="user,index in users" v-on:click="click_user(index)">{{user.name}}</div><br>    
 </div>

Answer №3

To enhance your code, consider creating a component and passing the user variable as a prop. Take a look at this example:

<users-list v-for="user in users" v-bind:user="user"></users-list>

For a functional demonstration, check out this link: https://jsfiddle.net/leocoder/tor13m26/1/

Avoid using v-html for this purpose as it is considered a bad practice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the value from every dynamically generated text box by its corresponding number

Trying to create a new Online Quiz System. The challenge I'm facing is extracting the values of each option associated with a specific question number. For example: Question # 1: a. elephant b. lion c. zebra Question # 2: a. green b. ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Initiate node.js execution upon system boot

Just diving into node.js. In the process of setting up integration tests for a node.js app using mocha, I found this helpful guide: Here's how I created a server: var http = require('http'); this.server = http.createServer(function (req, ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

React - Paths of images converting to relative when directly accessed via the address bar

Whenever I click on a route link, everything works perfectly. The images have the correct path in the DOM and load successfully. However, if I manually type the URL into the address bar with the route suffix included, like example.com/services, the image ...

Tips for handling the user's logged-in status in NativeScript Vue

I had a question about managing user login/logout, so I tried the following approach: store.commit('load_state'); store.subscribe((mutations, state) => { ApplicationSettings.setString('store', JSON.stringify(state)); }); new Vue( ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

What could be causing my component to not update after I modify the states?

When I make an ajax request and update the state with the response data, my list of items does not rerender as expected. Even though the state is updated successfully, the changes are not reflected in the UI. export class Tiles extends React.Component { ...

Enhancing user experience with dynamic element integration in jQuery's AutoComplete feature

In order to fulfill my requirement, I need to display a few options when the user enters at least three characters in one of the input fields, which may be added dynamically as well. Since the data is extensive, I am unable to load it at the beginning of ...

moment.js is unable to extract the time information from a timestamp

I'm having trouble converting a timestamp using moment.js from a json data set. When I try to use moment.format('MMMM Do YYYY, H:mm:ss'), the output is showing something like May 25th 2361, 0:00:00 for the timestamp 12351223423. This seems t ...

What techniques can I implement with puppeteer to efficiently warm up the cache?

I have a lengthy txt document containing around 1000 URLs that need to be accessed in order to warm up the Varnish cache. Since Puppeteer is required, it's crucial that there is important content loaded through AJAX calls. This is my initial attemp ...

The bi-directional data binding in Vuex-ORM is unable to monitor changes within a nested object

this query is linked to Two way data binding with Vuex-ORM i attempted to handle a user form using a watch with deep option. <template> <div id="app"> <div style="display: inline-grid"> <label for=" ...

Transmit information from a Vue.js application to a Laravel application

I've started working on two separate projects - one using Vue.js (created with vue create project_name) and the other using Laravel (created with laravel new project_name). My goal now is to transfer data from the Vue.js project to the Laravel project ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Having trouble implementing table row selection with semantic-ui table

I am currently in the process of adopting Semantic-UI, but I am encountering some issues. Specifically, I am struggling to make row selection work in a table. Below is the sample HTML I am using from Semantic-UI: <table class="ui selectable celled tab ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...