skip to Main Content

I have a button with id & name that I wanted to display their value but in my code nothing is displayed.
what is wrong with it ?

  <v-btn id="mytest" name="test" @click="addNewEntry">{{'add '}}</v-btn>


  methods: {
    addNewEntry() {
        document.getElementById("mytest").addEventListener('click', (event) => {        
        console.log('id value ' , event.target.id);
        console.log('name value ' , event.target.name)
      });
    },
}

2

Answers


  1. You already have an event listener attached to your method via @click="addNewEntry" so just do:

      methods: {
        addNewEntry(event) {
          console.log('id value ' , event.target.id);
          console.log('name value ' , event.target.name)
        },
      }
    
    Login or Signup to reply.
  2. I would recommend reading a bit more about vue v-model and event handling in vue

    But in short, when you add @click='methodName', that already adds an event listener so it is not needed to add document.getElementById("mytest").addEventListener(...) inside your method.

    One more thing, {{'add '}}: you should only put variables inside the {{}}. Since ‘add’ is a constant string here, then you can write this instead: ‘add ‘ {{ someVariable }}

    With that said, an answer to your question will use some of the points mentioned above:
    add a variables in your data to store the values for id and name. And use v-model to bind that variable with the input where the value is entered.

    data () {
     return {
      name: ''
     }
    },
    methods: {
     addNewEntry() {
       console.log('name value ' , this.name)
     }
    

    }

    And in your html input bind the relevant values

    <input type="text" v-model="name">
    <v-btn id="mytest" name="test" @click="addNewEntry">add {{ name }}</v-btn>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search