6

根据文档,Vue 对象的构造函数是这样管理的。

var vm = new Vue({
  created: function () { console.log("I'm created!"); }
});

但是,我不知道在创建 Vue 组件时如何做相应的事情。我已经尝试了以下但没有得到任何打印到控制台。

export default {
  created: function() { console.log("Component created!"); }
}

是否可以订阅/收听正在呈现的组件?我想通过下载一些数据并将其放入存储中来对该事件做出反应,以便组件携带的表将获取其信息以显示。

4

2 回答 2

7

在我的应用程序中,我倾向于mounted在组件安装后使用挂钩来加载一些 Ajax 数据。

我的应用程序中的示例代码:

Vue.component('book-class', {
    template: '#booking-template',
    props: ['teacherid'],
    data: function () {
        return{
            // few data items returned here..
            message: ''
        }
    },
    methods: {
        // Few methods here..
    },
    computed: {
      // few computed methods here...
    },
    mounted: function () {


        var that = this;
        $.ajax({
            type: 'GET',
            url: '/classinfo/' + this.teacherid,
            success: function (data) {
                console.log(JSON.stringify(data));

            }
        })
    }
});


new Vue({
    el: '#mainapp',
    data: {
        message: 'some message here..'
    }
});

但是,我也可以在生命周期中使用 created() 钩子。

在 Vue2 中,您有以下生命周期钩子:

在此处输入图像描述

于 2016-12-12T13:09:48.317 回答
1

组件没有像 app.js 这样的生命周期钩子。但他们有类似的东西。这解决了我的问题: https ://vuejs.org/v2/api/#updated

于 2019-04-15T08:29:03.410 回答