组件`mounted`在页面加载时触发两次

时间:2018-04-26 15:02:38

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

我有一个非常奇怪的错误,在页面加载组件@Entity @Table(name = "CAMPOS_OBRIGATORIOS") public class CamposObrigatorios { @EmbeddedId private CamposObrigatoriosID id; @ManyToOne @JoinColumn(name = "PERFIL_CMPOBR", referencedColumnName = "CODIGO_USRPERFIL") @MapsId("perfil") // maps 'perfil' attribute of embedded id private UsuarioPerfil usuarioPerfil; ... } mounted触发/运行两次?我的每个组件都代表一个页面,因此当我在beforeMount上加载页面时,mywebsite.com/contact函数Contact.vuemounted会触发/运行两次但如果我在beforeMount加载页面{1}} mywebsite.com/foo函数Contact.vuemounted触发/运行一次(这是我认为的?应该发生的事情。)

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

beforeMount

router/index.js

Page.vue:

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

Contact.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>

1 个答案:

答案 0 :(得分:1)

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

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

相关问题