【问题标题】:Vue.js hook on created event only once for a vue componentVue.js 只为一个 vue 组件挂钩创建的事件一次
【发布时间】:2018-04-02 12:18:57
【问题描述】:

问题

我有一个问题,created 事件挂钩不断被调用。这种偶数是否有任何类型的挂钩,例如“首次创建”或“首次安装”?如果可能,不要为每个组件附加垃圾代码。

兴趣点

这是一个示例,它显示了当您从页面“foo”切换到“bar”时,created 钩子是如何被调用的(您需要检查页面才能看到日志)。

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

【问题讨论】:

  • created 在每次安装组件时被调用。您需要one-time 挂钩的用例是什么?
  • 我正在使用 Vuex,我的“价格”页面正在通过我的 REST API (Laravel) 调用价目表。在创建时,我想调用我的操作,它异步获取我的价格,并且此操作正在调用我的 mutators,将我的“priceList”状态填充到价格数组。然后,负责以某种方式显示价格的组件对此变量执行 v-for(我通过价格组件上的 computed 公开了该变量)。我希望有一种干净的方法可以避免每次创建价格组件时都不断调用我的操作。

标签: javascript events vue.js vue-component


【解决方案1】:

考虑用&lt;keep-alive&gt;&lt;/keep-alive&gt; 包裹你的&lt;router-view&gt;&lt;/router-view&gt;,这样当你的路由改变时,路由的组件不会被重新创建:创建的钩子只会在最初创建时被调用一次。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 2018-01-30
    • 2018-07-27
    • 2022-12-10
    • 2020-02-22
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多