如何在Vue中的“ v-if”切换上更新画布?

时间:2018-07-13 19:07:12

标签: javascript vue.js

在画布上绘制类为progress-wrapper的类。每次切换列表后,如何更改此代码以重新绘制画布?自动取款机只绘制一次。

模板

<button @click="switcher = !switcher">SWITCH</button>

<transition name="fade">
    <li v-for="elements in myData" v-if="elements.key == getKey()">
        <span>{{elements.title}}</span>
        <div class="progress-wrapper" :data-value="elements.progress/100"></div>
    </li>
</transition>

脚本

data() {
    return {
        switcher: true,
    }

getKey(){
    if (this.switcher) {
        return 'KEY'
    } else {
        return 'ANOTHER KEY'
    }

样式

.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave {
  opacity: 0;
}

1 个答案:

答案 0 :(得分:1)

好的,您可以尝试一下。我已经发表了一些评论,以突出显示需要调整的部分。

<template>
  <div>
    <button @click="switcher = !switcher">SWITCH</button>

    <transition name="fade">
      <!-- is a good practice keep v-if and v-for in separate elements -->
      <div v-if="elements.key === currentKey">
        <!-- also you need to add key property when using a for loop -->
        <li 
          v-for="elements in myData"
          :key="elements.key"> 
          <span>{{ elements.title }}</span>
          <div 
            :data-value="elements.progress/100" 
            class="progress-wrapper"></div>
        </li>
      </div>
    </transition>
  </div>
</template>


<script>
export default {
  data() {
    return {
      switcher: true
    };
  },
  computed: {
    // this will return the new value of currentKey as soon as the value of switcher changes
    currentKey() {
      return this.switcher ? "KEY" : "ANOTHER KEY";
    }
  },
};
</script>

有关在同一节点中组合v-for和v-if的更多信息: https://vuejs.org/v2/guide/list.html#v-for-with-v-if