我有一个帮助过滤数据的功能。我在用户更改选择时使用 v-on:change
,但我还需要在用户选择数据之前调用该函数。我之前使用 ng-init
对 AngularJS
做了同样的事情,但我知道 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
中做到这一点?
您可以在 Vue 组件的 beforeMount 部分调用此函数:如下所示:
....
methods:{
getUnits: function() {...}
},
beforeMount(){
this.getUnits()
},
......
工作小提琴:https://jsfiddle.net/q83bnLrx/1/
Vue 提供了不同的生命周期钩子:
我列出了几个:
beforeCreate:在实例刚刚初始化之后,在数据观察和事件/观察者设置之前同步调用。 created:实例创建后同步调用。在这个阶段,实例已经完成了对选项的处理,这意味着已经设置了以下内容:数据观察、计算属性、方法、监视/事件回调。但是,安装阶段尚未开始,$el 属性将不可用。 beforeMount:在挂载开始之前调用:即将第一次调用渲染函数。挂载:在实例刚刚挂载后调用,其中 el 被新创建的 vm.$el 替换。 beforeUpdate:在数据发生变化时调用,在重新渲染和修补虚拟 DOM 之前。更新:在数据更改导致虚拟 DOM 重新渲染和修补后调用。
您可以查看完整列表 here。
您可以选择最适合您的钩子并将其钩子以调用您的函数,就像上面提供的示例代码一样。
您需要执行以下操作(如果您想在页面加载时调用该方法):
new Vue({
// ...
methods:{
getUnits: function() {...}
},
created: function(){
this.getUnits()
}
});
created
。
您也可以使用 mounted
https://v2.vuejs.org/v2/guide/migration.html#ready-replaced
....
methods:{
getUnits: function() {...}
},
mounted: function(){
this.$nextTick(this.getUnits)
}
....
请注意,当在组件上触发 mounted
事件时,并非所有 Vue 组件都被替换,因此 DOM 可能还不是最终的。
要真正模拟 DOM onload
事件,即在 DOM 准备好但页面绘制之前触发,请使用 mounted
内部的 vm.$nextTick:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
如果您在数组中获取数据,您可以执行以下操作。它对我有用
<template>
{{ id }}
</template>
<script>
import axios from "axios";
export default {
name: 'HelloWorld',
data () {
return {
id: "",
}
},
mounted() {
axios({ method: "GET", "url": "https://localhost:42/api/getdata" }).then(result => {
console.log(result.data[0].LoginId);
this.id = result.data[0].LoginId;
}, error => {
console.error(error);
});
},
</script>
methods: {
methodName() {
fetch("url").then(async(response) => {
if (response.status === 200) {
const data = await response.json();
this.xy = data.data;
console.log("Success load");
}
})
}
}