简体   繁体   English

Vue.js 只为一个 vue 组件钩住一次创建的事件

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

Question问题

I have an issue where created event hook keep being called.我有一个问题,即created事件挂钩不断被调用。 Is there any sort of hook-once for this kind of even, like "first-created" or "first-mounted"?对于这种偶数,是否有任何类型的 hook-once,例如“首次创建”或“首次安装”? 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).这是一个示例,显示了如果您从页面“foo”切换到“bar”(您需要检查页面以查看日志), created钩子如何继续被调用。

JSFiddle JSFiddle

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

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.考虑用<keep-alive></keep-alive>包裹你的<router-view></router-view> ,这样当你的路由改变时,路由的组件不会重新创建:创建的钩子只会最初创建时调用一次。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM