【问题标题】:Component `mounted` fires twice on page load组件“mounted”在页面加载时触发两次
【发布时间】:2018-10-07 08:22:38
【问题描述】:

我有一个非常奇怪的错误,页面加载组件mountedbeforeMount 触发/运行两次?我的每个组件都代表一个页面,所以当我在mywebsite.com/contact 上加载页面时,Contact.vue 函数mountedbeforeMount 会触发/运行两次,但如果我在mywebsite.com/foo 上加载页面,Contact.vue 函数@ 987654329@ 和 beforeMount 触发/运行一次(这是我认为? 应该发生的)。

知道为什么这些函数会执行两次吗?我有一些挑剔的设置,但它适用于动态模板。

router/index.js

const router = new Router({
routes: [
  {
      path: (window.SETTINGS.ROOT || '') + '/:slug',
      name: 'Page',
      component: Page,
      props: true
  },
]
})

Page.vue:

<template>
  <component v-if="wp" :is="templateComponent" v-bind:wp="wp"></component>
  <p v-else>Loading...</p>
</template>

<script type="text/javascript">

import { mapGetters } from 'vuex'
import * as Templates from './templates'

// Map templates
let templateCmps = {}
_.each(Templates, cmp => {
  templateCmps[cmp.name] = cmp
})

export default {

props: ["slug"],

components: {
  ...templateCmps

  // Example:
  // 'default': Templates.Default,
  // 'contact': Templates.Contact,
  // 'home': Templates.Home,
},

computed: {
  ...mapGetters(['pageBySlug']),

  wp() {
    return this.pageBySlug(this.slug);
  },

  templateComponent() {
    let template = 'default' // assign default template

    if (!_.isNull(this.wp.template) && this.wp.template.length)
      template = this.wp.template.replace('.php','').toLowerCase()

    return template
  }
},

created() {
  this.$store.dispatch('getPageBySlug', { slug: this.slug })
}
}
</script>

联系.vue:

<template>
    <main></main>
</template>

<script type="text/javascript">


export default {

    name: 'contact',

    mounted() {
      console.log('Contact::mounted') // this outputs twice
    },

    beforeMount() {
      console.log('Contact::beforeMount') // this outputs twice
    }
}

</script>

【问题讨论】:

  • 尝试给templateComponent添加一个观察者,看看值是否有任何不必要的变化?
  • 或者在return template之前简单地添加console.log(template)
  • 你能做一个 JS fiddle 让我们看看发生了什么吗?
  • 尝试打印出 console.log(this.$vnode.tag) 。这将显示组件名称和 ID;然后您可以检查是否有两个不同的组件正在渲染。我曾经遇到过这个问题,我的项目的 css 框架 (semantic-ui) 两次渲染一些 div 并将 display: 'none' 设置为其中一个。狡猾的混蛋。

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

我有(有)一个类似的问题。我对此不是 100% 确定,但我认为问题可能是由 vuex 引起的。 Vuex 有它自己的内部Vue 实例(在resetStoreVM() function 中创建here,在constructor() 中调用)。我怀疑Vue 的这个内部实例会导致重新创建一些组件,进而触发这些组件的生命周期事件多次触发。

如果不在vuex 中,您是否有可能在您的应用中创建多个Vue(即new Vue({}))实例?或者,是否有一些代码导致您的主要Vue 实例或Contact 组件被多次初始化?这就是我能想到的所有可能导致这种情况的原因。

【讨论】:

  • 我的项目中没有 vuex,并且我有一些特定的组件被安装了两次。此外,相同组件的其他实例也很好。还没找到原因,我试过用“key”,但是没有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2012-05-05
  • 2021-10-19
  • 1970-01-01
相关资源
最近更新 更多