我有一个帮助过滤数据的功能。当用户更改选择时,我正在使用 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)
});
}
在 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>
当我选择特定项目时,这很好用。然后,如果我点击所有让我们说 all floors
,它就可以工作。我需要的是当页面加载时,它调用 getUnits
方法,该方法将使用空输入执行 $http.post
。在后端,我以某种方式处理请求,如果输入为空,它将提供所有数据。
我如何在 vuejs2
中做到这一点?
我的代码:http: //jsfiddle.net/q83bnLrx
原文由 Phillis Peters 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以在 Vue 组件的 beforeMount 部分调用此函数:如下所示:
工作小提琴: https ://jsfiddle.net/q83bnLrx/1/
Vue 提供了不同的生命周期钩子:
我列出了几个:
beforeCreate :在实例刚刚初始化之后,在数据观察和事件/观察者设置之前同步调用。
created : 创建实例后同步调用。在这个阶段,实例已经完成了对选项的处理,这意味着已经设置了以下内容:数据观察、计算属性、方法、监视/事件回调。但是,安装阶段尚未开始,$el 属性将不可用。
beforeMount :在挂载开始之前调用:即将第一次调用渲染函数。
mount :在实例刚刚 挂载 后调用,其中 el 被新创建的
vm.$el
替换。beforeUpdate :在数据更改时调用,在重新渲染和修补虚拟 DOM 之前。
updated :在数据更改导致虚拟 DOM 重新渲染和修补后调用。
您可以在 此处 查看完整列表。
您可以选择最适合您的钩子并将其钩子以调用您的函数,就像上面提供的示例代码一样。