问题
我遇到了created
事件挂钩被调用的问题。对于这种类型的偶数,有没有任何类型的钩子,如“首次创建”或“首次安装”?如果可能,不为每个组件附加垃圾代码。
POI
这是一个示例,显示如果从页面“foo”切换到“bar”时如何保持调用created
挂钩(您需要检查页面以查看日志)。
HTML
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- use router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will be rendered as an `<a>` tag by default -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
JS
const Foo = { template: '<div>foo</div>', created: function() { console.log('foo created'); } };
const Bar = { template: '<div>bar</div>', created: function() { console.log('bar created'); } };
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
const router = new VueRouter({
routes // short for `routes: routes`
});
const app = new Vue({
router
}).$mount('#app');
答案 0 :(得分:1)
考虑将<router-view></router-view>
包裹在<keep-alive></keep-alive>
标签上,这样,当您的路线更改时,不会重新创建路线的组件,所创建的挂钩仅在最初创建时被调用一次