无法阻止 Vue JS (v2) 重用组件

Can't stop Vue JS (v2) from reusing components

我有一个 Vue 应用程序,它有条件地显示相同组件的集合,我想绑定到创建或安装的方法,但 Vue 一直重复使用早期的组件而不触发这些方法。我试过将组件包装在 keep-alive 标签中但没有效果。

下面的代码显示了您在页面上期望的内容:将 someVariable 更改为 'test1' 或 'test2' 显示了相关组件,但是 created/mounted 方法最多只触发 2次(例如,将 someVariable 更改为 'test1' 会记录创建和安装带有标签 type1 的 1 个组件,然后将其更改为 'test2' 只会记录另外 1 个带有标签 type3 的组件)。

目前使用 v2.1.10

HTML

<div id="app">
    <div v-if="someVariable === 'test1'">
        <keep-alive>
            <test-component data-type="type1"></test-component>
        </keep-alive>
    </div>

    <div v-if="someVariable === 'test2'">
        <keep-alive>
            <test-component data-type="type2"></test-component>
        </keep-alive>

        <keep-alive>
            <test-component data-type="type3"></test-component>
        </keep-alive>
    </div>
</div>

JS/Vue

Vue.component('test-component', {
    props: ['data-type'],
    template: '<div><p>In the component: {{ dataType }}</p></div>',
    created: function () {
        console.log('component created: ', this.dataType);
    },
    mounted: function () {
        console.log('component mounted: ', this.dataType);
    }
});

var app = new Vue({
    el: '#app',
    data: {
        someVariable: ""
    }
});

你应该在你的 someVariable 上使用观察者而不是试图挂钩 createdmounted hooks.

组件在第一次可见(呈现)时创建并安装。没有 "shown" 或 "hidden" 钩子。

参见https://vuejs.org/v2/guide/computed.html#Watchers

watch: {
  someVariable: function (newValue) {
    // test newValue and do what you have to do!
  }
}

对于您的具体示例,从第二个 if 中删除 keep-alive 应该可以解决问题 https://jsfiddle.net/z11fe07p/464/

有趣的是,vue 似乎 re-use 之前渲染的组件。因此,如果您在第一个 if 中有一个组件,当切换到具有 2 个组件的下一个 if 时,它将 re-use 一个组件并为块中的第二个组件创建一个新组件。当回到第一个 if 块时,它将 re-use 2 个已经渲染的组件之一。

如上所述,watcher 更适合这种情况,从而让您摆脱无法完全控制的地方的处理逻辑。您可以在文档 https://vuejs.org/v2/api/#updated

中看到此提示