0

Instead of having few methods that look like:

showDiv1(){ 
    this.showDiv1 = true
},
showDiv2(){ 
    this.showDiv2 = true
}

I am trying to create one like:

showElements(...elementNames){
     elementNames.forEach(name => {
           this.$data.name = true
     })
}

The idea was to pass one or few properties from data and when calling the method those elements would should up on screen.

In data I have something like this:

  data() {
      return {
           div1 = false,
           div2 = false
      }
  }

In html I tried to call the function on click in a couple of ways:

  <button @click="showElements('div1')">Show<button>
  <button @click="showElements(div1)">Show<button>
  <div v-if="div1">
       <p>Hello</p>
  </div>    

But nothing happens.

2 Answers 2

1

Seems like you have a syntax error. Instead of writing to your data object like this:

 data() {
      return {
           div1 = false,
           div2 = false
      }
  }

You should write it like this:

 data() {
      return {
           div1: false,
           div2: false
      }
  }

Make sure to only use syntax that fits an object in the data object. Then, you can call it like this:

 <button @click="showElements(div1)">Show<button>

One more thing, when accessing the data you don't actually need to write $data. Simply write 'this.name' in order to access your data.

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

2 Comments

Yair, thanks for the response. I did make a mistake here showing how the data looks but in my Vue component I have the right syntax. Also, I tried writing this.name without the $data part but still nothing happens on click.
What error do you get? You should probably post it here so we can get more information. Also if you can post your entire code that would be helpful, to see if there's anything else that might be causing this problem.
0

Dynamic property names are supposed to be accessed with bracket notation:

showElements(...elementNames){
     elementNames.forEach(name => {
           this[name] = true
     })
}

The method is supposed to be used like:

<button @click="showElements('div1')">Show<button>

3 Comments

Estus, I tried that but after clicking on the button nothing happens still.
You likely tried something different. It's workable. See codesandbox.io/s/damp-glade-1dk1o
My bad. I did not see/write it in my code. Thanks a lot!

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.