Leopold Kristjansson
Leopold Kristjansson

Reputation: 2784

How to pass a reference to a variable to a method - not the value of a variable - in VueJS

In my template I have this:

<input @input="myMethod(myVariableName)" />

Then I have myMethod

myMethod(variablePassed) {
  console.log(variablePassed)
}

What I receive is the value of the "variablePassed" (of course). But, is there a way for me to see which variable got passed?

Upvotes: 0

Views: 2184

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Yes you could do that by passing the variable wrapped inside a literal object {} and use Object.keys(varname)[0] to get its name and Object.values(varname)[0] to get its value:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      name: "john"
    }
  },
  methods: {
    myMethod(variablePassed) {
      
      console.log(Object.keys(variablePassed)[0])
       console.log(Object.values(variablePassed)[0])
      
    }
  }
})
#app {
  padding: 20px;
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  <input @input="myMethod({name})" class="form-control" />
</div>

Upvotes: 2

Related Questions