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

144

我有一个帮助筛选数据的函数。当用户更改选择时,我使用v-on:change,但我还需要在用户选择数据之前调用该函数。以前我使用ng-initAngularJS中完成相同操作,但我了解到在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 文件中,我使用 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>

当我选择特定项目时,这个功能很好用。如果我点击所有(比如所有楼层),它也可以工作。我需要的是当页面加载后,调用getUnits方法并执行带有空输入的$http.post。在后端,我已经处理了请求,如果输入为空,它会返回所有数据。

我该如何在vuejs2中实现这个?

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

7个回答

274

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

// .....
methods: {
    getUnits: function() { /* ... */ }
},
beforeMount() {
   this.getUnits()
},
// ......

工作的 JSFiddle:https://jsfiddle.net/q83bnLrx/1/

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

我列出了一些:

1. beforeCreate:在实例刚初始化之后、数据观察和事件/观察者设置之前同步调用。 2. created:在实例创建后同步调用。此时,实例已经处理完选项,也就是已经设置了数据观察、计算属性、方法、观察/事件回调。但是,挂载阶段尚未开始,$el属性还不可用。 3. beforeMount:在挂载开始之前调用:渲染函数即将被首次调用。 4. mounted:在实例刚刚被挂载后调用,其中el被新创建的vm.$el替换。 5. beforeUpdate:在数据更改之前,在重新渲染和修补虚拟DOM之前调用。 6. updated:在数据更改导致虚拟DOM重新渲染和修补之后调用。
您可以在 此处 查看完整列表。
您可以选择最适合您的钩子,并将其挂接到您的函数上,就像上面提供的示例代码一样。

@PhillisPeters,您能否添加更多的代码,或者创建一个fiddle(在线代码编辑器)来展示它。 - Saurabh
@PhillisPeters 请查看更新后的fiddle,我已经用setTimeout模拟替换了http post调用,现在您可以看到数据被填充到表格中。 - Saurabh
@GeorgeAbitbol 请随意根据情况更新答案。 - Saurabh
我的问题是我不知道在mounted()部分中如何使用“this”,并且我一直收到函数未定义的错误。上面使用了“this”,我明白这是解决我的问题的方法,但它在答案中没有突出显示。OP的问题是否类似于我的问题?添加一个调用以解决绑定问题会使这个答案更好吗? - mgrollins

35

如果你想在页面加载时调用该方法,你需要这样做:

new Vue({
    // ...
    methods:{
        getUnits: function() {...}
    },
    created: function(){
        this.getUnits()
    }
});

1
请尝试使用 created - The Alpha
1
@PhillisPeters 你可以使用 created 或 beforeMount。 - Saurabh

8

6

请注意,当组件上触发mounted事件时,并非所有Vue组件都已被替换,因此DOM可能尚未最终确定。

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

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

这里有一个关于安装组件顺序的解释:https://dev59.com/lqLia4cB1Zd3GeqPgEC6#44319825 - kissu

2
如果您得到一个数组的数据,可以按照以下方式操作。这对我来说有效。
    <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>

0
methods: {
  methodName() {
    fetch("url").then(async(response) => {
      if (response.status === 200) {
        const data = await response.json();
        this.xy = data.data;
        console.log("Success load");
      }
    })
  }
}

2
请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Mark Rotteveel

0

你可以使用created()方法来实现。它会在页面完全加载后触发。

 created:function(){
        this.fillEditForm();
    },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接