当一个函数在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>
答案 0 :(得分:3)
似乎mounted()
是从Vue构造函数触发的,即在vm
变量可以被分配之前。因此,vm
引用不会丢失,但在调用hello()
时仍未定义。
稍后在timeout()
构造函数已返回并分配Vue
变量时调用vm
回调。这些事件的年表也在控制台中可见。
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;