Anwar
Anwar

Reputation: 4246

Vue.js hook on created event only once for a vue component

Question

I have an issue where created event hook keep being called. Is there any sort of hook-once for this kind of even, like "first-created" or "first-mounted"? If possible, no junk code to attach for each component.

POI

Here is an example that shows how the created hook keeps being called if you switch from page "foo" to "bar" (you will need to inspect the page to see the log).

JSFiddle

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');

Upvotes: 3

Views: 4066

Answers (1)

Andres Castillo
Andres Castillo

Reputation: 51

Consider wrapping your <router-view></router-view> with <keep-alive></keep-alive>, so that when your route changes, the component for the routes isn't recreated: the created hook will only be called once when it is created initially.

<router-view>
  {({ Component }) => (
    <keep-alive>
      <Component />
    </keep-alive>
  )}
</router-view>

Upvotes: 5

Related Questions