【发布时间】:2018-04-02 12:18:57
【问题描述】:
问题
我有一个问题,created 事件挂钩不断被调用。这种偶数是否有任何类型的挂钩,例如“首次创建”或“首次安装”?如果可能,不要为每个组件附加垃圾代码。
兴趣点
这是一个示例,它显示了当您从页面“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');
【问题讨论】:
-
created在每次安装组件时被调用。您需要one-time挂钩的用例是什么? -
我正在使用 Vuex,我的“价格”页面正在通过我的 REST API (Laravel) 调用价目表。在创建时,我想调用我的操作,它异步获取我的价格,并且此操作正在调用我的 mutators,将我的“priceList”状态填充到价格数组。然后,负责以某种方式显示价格的组件对此变量执行 v-for(我通过价格组件上的
computed公开了该变量)。我希望有一种干净的方法可以避免每次创建价格组件时都不断调用我的操作。
标签: javascript events vue.js vue-component