saz*_*azr 9 vue.js vue-router vue-component vuejs2
我有一个非常奇怪的错误,在页面加载组件mounted和beforeMount火/运行两次?我的每个组件都代表一个页面,所以当我mywebsite.com/contact在Contact.vue函数上加载页面mounted并beforeMount激活/运行两次但是如果我mywebsite.com/foo在Contact.vue函数上加载页面mounted并beforeMount激活/运行一次(这是我认为的?应该发生).
知道为什么这些函数会执行两次吗?我有一些挑剔的设置,但它适用于动态模板.
router/index.js:
const router = new Router({
routes: [
{
path: (window.SETTINGS.ROOT || '') + '/:slug',
name: 'Page',
component: Page,
props: true
},
]
})
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
Contact.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>
Run Code Online (Sandbox Code Playgroud)
我也有类似的问题。我对此不是 100% 确定,但我认为问题可能是由vuex. Vuex有它自己的内部实例Vue(在 中调用的resetStoreVM()函数中创建constructor())。我怀疑这个内部实例会Vue导致某些组件被重新创建,进而触发这些组件的生命周期事件多次触发。
如果不在 中,您是否可能在应用程序中vuex创建多个Vue(ie ) 实例?new Vue({})或者,是否有一些代码导致您的主Vue实例或Contact组件被多次初始化?这就是我能想到的可能导致这种情况的全部。