如何在页面加载时调用vue.js函数

Phi*_*ers 74 javascript vue.js vuejs2

我有一个有助于过滤数据的功能.我在v-on:change用户更改选择时使用,但我甚至需要在用户选择数据之前调用该函数.我AngularJS以前使用过的方法也一样,ng-init但据我所知,没有这样的指令vue.js

这是我的功能:

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) {
            console.log(response.data);
            this.units = response.data;
        }, function (response) {
            console.log(response)
        });
    }
Run Code Online (Sandbox Code Playgroud)

blade文件中我使用刀片表单来执行过滤器:

<div class="large-2 columns">
        {!! Form::select('floor', $floors,null, ['class'=>'form-control', 'placeholder'=>'All Floors', 'v-model'=>'floor', 'v-on:change'=>'getUnits()' ]) !!}
    </div>
    <div class="large-3 columns">
        {!! Form::select('unit_type', $unit_types,null, ['class'=>'form-control', 'placeholder'=>'All Unit Types', 'v-model'=>'unit_type', 'v-on:change'=>'getUnits()' ]) !!}
    </div>
Run Code Online (Sandbox Code Playgroud)

当我选择特定项目时,此工作正常.然后,如果我点击所有让我们说all floors,它的工作原理.我需要的是当页面加载时,它调用getUnits将执行$http.post空输入的方法.在后端,我已经处理了请求,如果输入为空,它将提供所有数据.

我怎么能这样做vuejs2

我的代码:http://jsfiddle.net/q83bnLrx

Sau*_*abh 152

您可以在Vue组件的beforeMount部分中调用此函数 :如下所示:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......
Run Code Online (Sandbox Code Playgroud)

工作小提琴:https://jsfiddle.net/q83bnLrx/1/

Vue提供了不同的生命周期钩子:

我列出的几个是:

  1. beforeCreate:在数据观察和事件/观察器设置之前,刚刚初始化实例后同步调用.
  2. created:创建实例后同步调用.在此阶段,实例已完成处理选项,这意味着已设置以下内容:数据观察,计算属性,方法,监视/事件回调.但是,安装阶段尚未开始,$ el属性尚未可用.
  3. beforeMount:在安装开始之前调用:渲染函数即将首次调用.
  4. 已安装:刚安装实例后调用,其中el由新创建的替换vm.$el.
  5. beforeUpdate:在重新呈现和修补虚拟DOM之前,在数据更改时调用.
  6. updated:在数据更改后调用导致重新呈现和修补虚拟DOM.

您可以在此处查看完整列表.

您可以选择最适合您的挂钩并将其挂钩以调用您的功能,就像上面提供的示例代码一样.


The*_*pha 27

你需要做这样的事情(如果你想在页面加载时调用方法):

new Vue({
    // ...
    methods:{
        getUnits: function() {...}
    },
    created: function(){
        this.getUnits()
    }
});
Run Code Online (Sandbox Code Playgroud)


Ber*_*rah 6

你也可以使用 mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....
Run Code Online (Sandbox Code Playgroud)


rus*_*tyx 6

请注意,当mounted在组件上触发事件时,并非所有 Vue 组件都被替换,因此 DOM 可能还不是最终的。

要真正模拟 DOMonload事件,即在 DOM 准备好后但在绘制页面之前触发,请在内部使用vm.$nextTickmounted

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}
Run Code Online (Sandbox Code Playgroud)