Search code examples
svgvue.jspathv-for

vue svg path with v-for


I am trying to bind the various coordinates in an svg path to data() in vue.js

<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
       <g>
           <path v-for="n in 50" d="'M0 ' + (n*10) + ' L500 ' + (n*10)" fill="white" stroke="lightgray" />
           <path v-for="n in 50" d="{'M0 ' + (n*10) + ' L500 ' + (n*10)}" fill="white" stroke="lightgray" />
       </g>
</svg>

The alternative is to call a method and that works,

<path v-for="n in 400" :d="gridy(n)" fill="white" stroke="lightgray" />

The gridy() method

gridy(n) {
                return "M0" + " " + (n * 10) + " L500 " + (n * 10)
            },

Is the way I tried to do this without calling a method incorrect?

Thanks


Solution

  • You just have to bind the d attribute of the SVG like so:

    <path v-for="n in 50" :d="'M0 ' + (n*10) + ' L500 ' + (n*10)" fill="white" stroke="lightgray" />
    

    Working example:

    new Vue({el: '#app'})
    Vue.config.devtools = false
    Vue.config.productionTip = false
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <main id="app">
    <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
           <g>
               <path v-for="n in 50" :d="'M0 ' + (n*10) + ' L500 ' + (n*10)" fill="white" stroke="lightgray" />
           </g>
    </svg>
    </main>