2

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks for answer, I mean click here for specific object
you can pass the parameter into test(parameter) to use specific object
2

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.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.