user761100
user761100

Reputation: 2317

Vue.js: How to change set of properties based on another property

I have a set of divisions named as divReports0, divReports1, divReports2, etc. These are also properties in my vue model. I want to show/hide these divisions based on a value selected from a SELECT box, available in the selectedReport property. Here is the code I am having trouble with.

    showHideDivision: function()
    {
        for (var j=0; j < this.reportsList.length; j++) 
        {
            var divName = 'divReports' + this.reportsList[j]['value'];
            if (this.reportsList[j]['value'] == this.selectedReport)
            {
                console.log('Show:' + divName );
                //this.divReports+eval(this.reportsList[j]['value']) = true
            }   
            else
            {
                console.log('Hide:' + divName );
            }
        }

    },

I have the divsion name property to control in the divName variable. How can I assign a value to the divName property? (e.g. this.eval(divName) = false)

Upvotes: 0

Views: 840

Answers (1)

Roy J
Roy J

Reputation: 43899

Since the goal is to display only one div at a time, you should have a variable that indicates which one is to display, rather than having a boolean for each to indicate whether it is displayed.

In any case, numbering variable names (this.divReportsX where X is a variable) is almost always an indicator that you should be using an array rather than individual scalars.

In the example below, I use the range form of v-for to count my divs from 1 to 3 (or however many you want). There is selectedReport to indicate which div is shown. And just for fun, I included a computed showHide that gives you a boolean indexed by the div number so you can use v-show=showHide[div]

new Vue({
  el: '#app',
  data: {
    howManyDivs: 3,
    selectedReport: 1
  },
  computed: {
    showHide() {
      const result = [];

      for (let i=1; i <= this.howManyDivs; ++i) {
        result[i] = i === this.selectedReport;
      }
      return result;
    }
  }
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <select v-model="selectedReport">
    <option v-for="div in howManyDivs" :value="div">Show {{div}}</option>
  </select>
  <div v-for="div in howManyDivs" v-show="showHide[div]">
    Report div
    <h1>** {{div}} **</h1>
  </div>
  <div v-for="div in howManyDivs">
    {{div}}: {{showHide[div]}}
  </div>
</div>

Upvotes: 1

Related Questions