Vue模板-当列表中的项目ID等于变量时动态添加类名

时间:2019-05-16 13:14:49

标签: vue.js

我有一个很大的svg贴图,需要根据用户输入突出显示某个部分。

svg本质上是单个文件组件。

模板:

<template>
svg version="1.1" xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 350 600 450">
        <g>
<path id="X" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........" />
<path id="Y" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
<path id="Z" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
        </g>
    </svg>
</template>

脚本:

 module.exports = {
        name: 'map',
        props:['userSelect'],
        methods: {
          checkProp: function() {
            console.log(userSelect) 
//prop works as expected
          }
        }

我需要的是,当id与userSelect匹配时,我应该在现有的“ class1”中添加另一个名为“ class2”的类。 有人有主意吗?

2 个答案:

答案 0 :(得分:2)

您可以使用v-bind:shorthand :

示例:

<template>
svg version="1.1" xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 350 600 450">
        <g>
<path id="X" :class="setClass('X')" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........" />
<path id="Y" :class="setClass('Y')" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
<path id="Z" :class="setClass('Z')" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
        </g>
    </svg>
</template>
 module.exports = {
        name: 'map',
        props:['userSelect'],
        methods: {
          setClass (id) {
            return id === userSelect ? 'class1 class2' : 'class1'
          }
        }

答案 1 :(得分:0)

我将创建一个组件并使用一个计算所得的属性,以便将其值进行缓存:

MyPath组件

<template>
  <path v-bind="$attrs" :class="pathClass"/>
</template>

<script>
export default {
  props: ['userSelect'],
  computed() {
    pathClass() {
      return this.$el.id === this.userSelect;
    }
  }
}
</script>

然后地图模板变为:

<template>
svg version="1.1" xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 350 600 450">
        <g>
<my-path id="X" :user-select="userSelect" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........" />
<my-path id="Y" :user-select="userSelect" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
<my-path id="Z" :user-select="userSelect" class="class1" d="4,522.87L164.95,523.31L166.15,524.54L167.29,524.57L169.47,525.42L170.72,525.22L172.59,523.7........"/>
        </g>
    </svg>
</template>