The @click directive in vuex does not function properly within the Vue component

This content is from my online shop.

getters: {
  getFormattedUsers (state) {
    state.users.forEach(v => {
      v.fullname = `${capitalize(v.fname)} ${capitalize(v.lname)}`
      v.created_from_now = moment(v.created_at).fromNow()
      v.approve_button = `<button @click="openApproveModal" class="btn btn-primary">Approve</button>`     
    })

    return state.users
  }
}

When the component is mounted, it does the following:

async mounted () {
  await this.initializeUsers()

  $('#dataTable').DataTable({
    data: this.getFormattedUsers(),
    columns: [
      {data: 'fullname'},
      {data: 'username'},
      {data: 'is_approved'},
      {data: 'created_from_now'},
      {data: 'approve_button'}
    ]
  })
}

If you click on the Approve Button,

methods: {
  openApproveModal (id) {
    console.log('Approved!')
  }
}

However, when tested, the function did not execute as expected.

Here is a representation of what the table in my component looks like:

 <table class="table table-bordered" id="dataTable">
   <thead>
     <tr>
       <th>Name</th>
       <th>Username</th>
       <th>Status</th>
       <th>Registration Date</th>
       <th width="5">Action</th>
     </tr>
   </thead>
 </table>

Answer №1

It's important to note that modifying reactive state inside a getter is not recommended. This can result in infinite loops and is generally considered a poor practice.

Consider this as a warning sign:

v.approve_button = `<button @click="openApproveModal" class="btn btn-primary">Approve</button>`

If you are trying to inject this into the DOM using v-html, it will not work. v-html only accepts HTML, whereas your input seems to be a Vue template.

Without knowing the full context of the template, I cannot offer a specific solution. However, it is best to avoid using v-html whenever possible (not just due to XSS concerns, but also because it may go against the principles of Vue).


For a simplified demonstration of your goal:

// Attempting to create a Vue button

function handleClick() {
  alert('You will not see this')
}

const app = document.querySelector('#app')
app.innerHTML = '<button @click="handleClick">Not Working</button>'

// A proper approach

const componentInstance = new Vue({
  template: '<button @click="handleClick">Working</button>',
  methods: {
    handleClick() {
      alert('Works!')
    }
  }
})

componentInstance.$mount()
app.appendChild(componentInstance.$el)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></div>

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

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

"Enhance User Experience with Material UI Autocomplete feature that allows for multiple

I am encountering an issue with a material ui auto component that I am currently working on. The component's code looks like this: <Autocomplete multiple options={props.cats} defaultValue={editRequest? ...

Tips for eliminating the glowing effect when pressing down on the thumb of the material ui slider

Visit Material-UI documentation for Slider component. Despite setting the disabled flag for the entire slider, the thumb continues to show a halo effect when clicked. ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

NgModel in Angular Datapicker does not successfully transmit value

My page features a form that functions as a filter search, with one of the fields being a date field. I have configured the Angular UI datepicker plugin (https://github.com/angular-ui/ui-date) and the calendar pops up when I focus on the date field. Howe ...

Discover the concealed_elem annotations through the power of JavaScript

As I work on my new website, I am struggling with narrowing down the web code. I came across a solution that seems fitting for what I need, but unfortunately, I can't seem to make it work: I attempted the non-jQuery solution, however, I must be missi ...

Is it possible to verify if a function is invoked using Jest, Typescript, and ts-jest in action?

Currently, I'm testing the functionality of this code snippet: src/helpers/CommentHelper.ts: export default class CommentHelper { gitApiObject: GitApi.IGitApi ; constructor(gitApiObject: GitApi.IGitApi) { this.gitApiObject = gi ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

Intersecting object identification, fresh Function

I'm currently utilizing the "Sinova / Collisions" library on GitHub along with Node.js. The library can be found at https://github.com/Sinova/Collisions. I am in need of a function that allows me to delete all data at once, as the current function for ...

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...

Create a duplicate of the prop object by transferring it to a fresh data

Structure of Vue components; UserList.Vue (parent component) UserEditor.vue (child component) A table displaying users is present, when a user is selected, the selectedUser property is updated with the chosen user (within UserList.vue); selectedUser: ...

Tips for presenting the retrieved data from the database in a user-friendly format

$ //First step involves running the PHP code that executes the SQL query to retrieve data from the database, storing it in get_row1, and sending it as a response to Ajax$ <?php $connect = mysql_connect("localhost", "root", ""); $data = mysq ...

Dividing ReactJS into different assemblies

I have a flexible .NET application that utilizes plugins to load controllers, views, and components from different assemblies. I am interested in learning React (completely new to me) and I have a question. Can React split its components into separate as ...

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Unable to locate the "stage-2" preset in the specified directory

In my webpack.base.config.js, I am using the presets: ['stage-2']: { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: ['stage-2'] } }, However, an error occurs: Couldn ...

VUE textarea embedded within a Webview2 control

How do I utilize Webview2 to input a value into a textarea in VUE? document.querySelector("#app > div > main > div > aside > div.container.fluid > div:nth-child(2) > div > form > div > div > div.v-input__slot > div > ...