How to call a vue.js function on page load
我有一个帮助过滤数据的功能。当用户更改选择时,我正在使用 v-on:change 但我还需要在用户选择数据之前调用该函数。我以前使用 ng-init 对 AngularJS 做了同样的事情,但我知道 vue.js
中没有这样的指令
这是我的功能:
|
1
2 3 4 5 6 7 8 9 10 |
getUnits: function () {
var input = {block: this.block, floor: this.floor, unit_type: this.unit_type, status: this.status}; this.$http.post(‘/admin/units’, input).then(function (response) { |
在 blade 文件中,我使用刀片表单来执行过滤器:
|
1
2 3 4 |
{!! Form::select(‘floor’, $floors,null, [‘class’=>‘form-control’, ‘placeholder’=>‘All Floors’, ‘v-model’=>‘floor’, ‘v-on:change’=>‘getUnits()’ ]) !!}
{!! Form::select(‘unit_type’, $unit_types,null, [‘class’=>‘form-control’, ‘placeholder’=>‘All Unit Types’, ‘v-model’=>‘unit_type’, ‘v-on:change’=>‘getUnits()’ ]) !!} |
当我选择一个特定的项目时,这很好用。然后,如果我单击所有让我们说 all floors,它就可以工作。我需要的是当页面加载时,它调用 getUnits 方法,该方法将使用空输入执行 $http.post 。在后端,我以某种方式处理请求,如果输入为空,它将提供所有数据。
如何在 vuejs2 中做到这一点?
我的代码:http://jsfiddle.net/q83bnLrx
您可以在 Vue 组件的 beforeMount 部分调用此函数:如下所示:
|
1
2 3 4 5 6 7 8 |
….
methods:{ getUnits: function() {…} }, beforeMount(){ this.getUnits() }, …… |
工作小提琴:https://jsfiddle.net/q83bnLrx/1/
Vue 提供了不同的生命周期钩子:
我列出了几个:
您可以在此处查看完整列表。
您可以选择最适合您的钩子,并像上面提供的示例代码一样钩子来调用您的函数。
- @PhillisPeters 您可以添加更多代码,或者创建一个小提琴。
- @PhillisPeters 请查看更新的小提琴,我已将 http post call 替换为 setTimeout 进行模拟,现在您可以看到表格中填充的数据。
- @GeorgeAbitbol 请随时相应地更新答案。
- 我的问题是我不知道在mounted() 部分中使用”this”,并且出现函数未定义错误。上面使用了”这个”,我发现这是我的问题的解决方案,但答案中没有突出显示。 OP的问题与我的相似吗?添加一个标注来解决绑定问题会使这个答案更好吗?
你需要做这样的事情(如果你想在页面加载时调用该方法):
|
1
2 3 4 5 6 7 8 9 |
new Vue({
// … methods:{ getUnits: function() {…} }, created: function(){ this.getUnits() } }); |
- 尝试 created 代替。
- @PhillisPeters 您可以使用 created 或 beforeMount。
你也可以使用 mounted
来做到这一点
https://vuejs.org/v2/guide/migration.html#ready-replaced
|
1
2 3 4 5 6 7 8 |
….
methods:{ getUnits: function() {…} }, mounted: function(){ this.$nextTick(this.getUnits) } …. |
请注意,当 mounted 事件在组件上触发时,并非所有 Vue 组件都被替换,因此 DOM 可能还不是最终的。
要真正模拟 DOM onload 事件,即在 DOM 准备好但页面绘制之前触发,请在 mounted:
内部使用 vm.$nextTick
|
1
2 3 4 5 |
mounted: function () {
this.$nextTick(function () { // Will be executed when the DOM is ready }) } |
如果你得到数组中的数据,你可以像下面这样。它对我有用
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<template>
{{ id }} </template> import axios from“axios”; export default { } |
来源:https://www.codenong.com/40714319/
