首页 > 解决方案 > Vue 在 v-if 参数更改时不更新相同类型的组件

问题描述

我有一个自定义的切换组件,在 Vue 中从头开始制作。

<template>

  <div :class="{Switch: true, disabled: disabled}" @click="toggle" :title="disabled ? disabledtitle : ''">

    <div :class="{Background: true, active: isToggled}"></div>
    <div :class="{Toggle: true, active: isToggled}"></div>

  </div>

</template>

<script>

  export default {

    name: 'Toggle',
    props: {

      toggled: {

        type: Boolean,
        default: false

      },
      disabled: {

        type: Boolean,
        default: false

      },
      disabledtitle: {

        type: String,
        default: ''

      }

    },
    data () {

      return {

        isToggled: false

      }

    },
    methods: {

      toggle () {

        if(this.disabled)
          return

        this.isToggled = !this.isToggled
        this.$emit('input', this.isToggled)

      }

    },
    mounted () {

      this.isToggled = this.toggled

    }

  }

</script>
...

它在另一个组件中有多个实例,如下所示:

<template>

    <div v-if="category === 'Basic'" class="Basic">

        <Toggle :toggled="config.isToggledThisOption" @input="updateConfig($event, 'isToggledThisOption')" />

    </div>

    <div v-else-if="category === 'Other'" class="Other">

        <Toggle :toggled="config.isToggledOtherOption" @input="updateConfig($event, 'isToggledOtherOption')" />

    </div>

</template>
...

还有一个菜单,可以在类别之间切换(更改category变量)这很好用,但问题是,toggled在类别之间切换时道具不会更新。

我设法追踪它,问题如下:

每当值发生category变化时,<Toggle />组件不会更新。它始终保持不变,即使在检查元素中,也不会发生更新。mounted()也不会再次执行,仅在重新加载页面时(即使那样,并非所有<Toggle />s'mounted()函数都被执行)。

我是否需要向组件添加某种 id/标识符,以便重新安装/重新渲染/重新启动它?

标签: javascriptvue.jsconditional-statementstoggle

解决方案


推荐阅读