Dynamically adding columns in Vue [SOLVED]

I would like to create a table in which the number of columns is being changed dynamically
If I hard code their number in CSS, the columns are there.
To render them dynamically I use Vue compute method, but it doesn’t work. I use Vue for everything else, so I have to keep it.
Is this the right approach?

var app = new Vue({
    el: '#app',
    data: {    
        //in my real app, numOfColumns is being changed dynamically    
        numOfColumns: 3
    },
    computed: {
        gridStyle() {
            return {
                "grid-template-columns: 12vw repeat (" + this.numOfColumns + ", 1fr);";
            }
          //I also tried:
          // gridTemplateColumns: "12vw repeat (" + this.numOfColumns + ", 1fr);";
        
        }
    },
})
 <div id="some-div" :style="gridStyle">
            <div class="smaller-div"></div>
            <div class="smaller-div"></div>
        </div>
#some-div {
    width: 300px;
    height: 250px;
    background-color: purple;
    display: grid;
     /*this would be a harcoded approach */
    /* grid-template-columns: repeat(3, 1fr); */
}

.smaller-div {
    /* display: block; */
    margin: 5px;
    width: 50px;
    height: 50px;
    background-color: bisque;
}

Here is the (not) working example.
https://codepen.io/Kosiada/pen/RddEVj

Have never used Vue, but are you sure this is the correct syntax to render styles?

Your output is simply returning {{ numOfColumns }}.

2 Likes

Yes, the syntax was not quite right. The semicolon in the end of the string messed everything. :grimacing:
The correct one is:

computed: {
      gridStyle() {
        console.log("hello")
          return {
              "grid-template-columns": "repeat(" + this.numOfColumns + ", 1fr)"
              // order: 1
          }    
      }
  },

It took a lot of testing to figure it out.