0

Super simple question but i've never been able to solve it. Say we have some data:

section: {
  option1: true,
  option2: true
}

and on a button we have:

<button @click="toggle(option1)">

How do I dynamically paste 'option1' arg into something like this:

toggle(opp){
console.log(this.section.opp)
}

Because currently it's literally looking for this.section.opp, and opp doesn't exist in the data.

3
  • 4
    toggle('option1') and console.log(this.section[opp]) - just as it always is in javascript :p Commented Mar 23, 2022 at 7:32
  • Legend. Sometimes I just have a brain fart hey. Commented Mar 23, 2022 at 7:38
  • @JackSumner I added an answer. Hope that will work as per your expectation. Commented Mar 23, 2022 at 9:29

1 Answer 1

1

Use this.section[opp] instead of this.section.opp as opp contains dynamic value and can not access directly with dot(.) notation as it is containing a different value.

Working Demo :

new Vue({
  el: '#app',
  data: {
    section: {
      option1: true,
      option2: true
    },
    result: null
  },
  methods: {
    toggle(opp) {
      this.result = this.section[opp];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="toggle('option1')">Click Me</button>
  <p>Result: {{ result }}</p>
</div>

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

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.