如何在Vue.js中动态渲染svg形状元素的数量?

时间:2019-11-02 07:00:55

标签: vue.js svg

我的svg形状元素及其属性是从服务器端查询的,然后 如何在不使用静态html标记的情况下在vue中动态渲染以使用v-for?

1 个答案:

答案 0 :(得分:0)

听起来像Render Function的工作。例如:

创建SvgElement.vue

render: function (createElement) {
    return createElement(
        this.shapeType,
        {
            attrs: this.attrObj
        },
        this.$slots.default
    )
},
props: {
    shapeType: {
        type: String,
        required: true
    },
    attrString: {
        type: string
    }
},
computed: {
    attrObj() {
        // Convert this.attrString into an object
        // eg return { cx: 50, cy: 50, r: 10, fill: 'red' }
    }
}

然后在MyComponent.vue

中使用
<template>
    <svg width="400" height="400">
        <SvgElement
            v-for="svg in svgArray"
            :key="svg.key"
            :shapeType="svg.type"
             :attrString="svg.attr"
        />
    </svg>
</template>

<script>
import SvgElement from './SvgElement'
export default {
    components: {
        SvgElement
    },
    data () {
        return {
            svgArray: [
                { type: 'rect', attr: 'attrString', key: 'shape1' },
                { type: 'circle', attr: 'attrString', key: 'shape2' }
            ]
        }
    }
}
</script>