dedi wibisono
dedi wibisono

Reputation: 533

Is possible create event on click in object - Vue JS

new Vue({
  el: "#app",
  data: {
    checking: [
      { text: "Event 1 <a :click='test()' class='click'>click here</a>" },
      { text: "Event 2" },
      { text: "Event 3" },
      { text: "Event 4" }
    ]
  },
  methods: {
    test() {
      console.log("clicked")
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.2/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(check, i) in checking" :key="i" v-html="check.test"></li>
  </ul>
</div>

Is it possible to create an event click in an object? I tried but always failed, maybe something's wrong in my code. Thank you.

here is my full code fiddle

Upvotes: 2

Views: 625

Answers (3)

Manuel Abascal
Manuel Abascal

Reputation: 6362

You can't do it. According to Vue API's documentation:

Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates. If you find yourself trying to compose templates using v-html, try to rethink the solution by using components instead.

It's even discouraged:

Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS attacks. Only use v-html on trusted content and never on user-provided content.

Upvotes: 2

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

you can try like below, hope resolve your problem, fiddle

template:

 <div id="app">
  <ul>
    <li v-for="(check, i) in checking"  :key="i">
     {{check.text}} <a @click='test' class='click'>click here</a>
    </li>
  </ul>
</div>

Vue instance:

new Vue({
      el: "#app",
      data: {
        checking: [
          { text: "Event 1" },
          { text: "Event 2" },
          { text: "Event 3" },
          { text: "Event 4" }
        ]
      },
      methods: {
        test() {
          console.log("clicked")
        }
      }
    })

Screen will look like this:

enter image description here

Upvotes: 2

Swimmer F
Swimmer F

Reputation: 903

You can add click events with the v-on:click property:

new Vue({
  el: "#app",
  data: {
    checking: [
      { text: "Event 1" },
      { text: "Event 2" },
      { text: "Event 3" },
      { text: "Event 4" }
    ]
  },
  methods: {
    test(input) {
      console.log("Element " + (input + 1 ) +" clicked")
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.2/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(check, i) in checking" :key="i" >{{ check.text }} <a v-on:click="test(i)">click here</a></li>
  </ul>
</div>

Upvotes: 1

Related Questions