'vm'对象在Vue实例外部并且调用inside方法已挂载undefined

时间:2017-06-27 22:16:51

标签: javascript vuejs2

当一个函数在vue实例之外使用并在mount方法内部传递时,为什么对'vm'的引用会丢失?

https://jsfiddle.net/z9u39hgu/5/

var vm = new Vue({
    el: '#app-4',
    data: {
        isLoading: true
    },
    mounted: function() {
        hello();
    }
});


function hello() {
    console.log(JSON.stringify(vm));
    //vm.isLoading = true;
    setTimeout(function() {
        console.log(JSON.stringify(vm, replacer));
        //vm.isLoading = false;
    })
}

//Extra code ignore
seen = []; 

var replacer = function(key, value) {

if (value != null && typeof value == "object") {
    if (seen.indexOf(value) >= 0) {
        return;
    }
    seen.push(value);
}
return value;

};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app-4">
    <p v-if="isLoading">Vuejs loading...</p>
</div>

1 个答案:

答案 0 :(得分:3)

似乎mounted()是从Vue构造函数触发的,即在vm变量可以被分配之前。因此,vm引用不会丢失,但在调用hello()时仍未定义。

稍后在timeout()构造函数已返回并分配Vue变量时调用vm回调。这些事件的年表也在控制台中可见。

&#13;
&#13;
var vm = new Vue({
    el: '#app-4',
    data: {
        isLoading: true
    },
    mounted: function() {
        hello();
    }
});


function hello() {
    console.log("before timeout: " + typeof(vm));
    //vm.isLoading = true;
    setTimeout(function() {
        console.log("after timeout: " + typeof(vm));
        //vm.isLoading = false;
    })
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app-4">
    <p v-if="isLoading">Vuejs loading...</p>
</div>
&#13;
&#13;
&#13;