vue的初始化写法?

var vm = new Vue({
    el: '#app',
    data: {
        cc: ''
    },
    methods: {
        ajax: function() {
            var _this = this;
            axios.get('/mock.json', {}).then(function(res) {
                _this.init(res);
            }).catch(function(res) {
                console.log(res);
            });
        },
        init: function(res) {
            this.cc = res.data.cc;
        }
    }
});
vm.ajax();

希望页面一开始加载完毕就发请求获取数据,ajax函数是通过vm.ajax()进行调用的,但我不想定义vm,只按照下面的结构写的话,能否在页面一载入时调用ajax函数?

正打算用钩子函数试试……除此之外还有办法吗?

阅读 15.9k
3 个回答

生命周期、如果是vue2.0的话、有mouted函数

贴张生命周期图

clipboard.png

按照你的写法

var vm = new Vue({
    el: '#app',
    data: {
        cc: ''
    },
    methods: {
        ajax: function() {
            var _this = this;
            axios.get('/mock.json', {}).then(function(res) {
                _this.init(res);
            }).catch(function(res) {
                console.log(res);
            });
        },
        init: function(res) {
            this.cc = res.data.cc;
        }
    },
    mouted:function(){
        this.ajax();
    }
});

回答的不错,就是单词拼错了,老铁

mounted:function(){
        this.ajax();
    }
推荐问题