<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.5.2/qs.min.js"></script>
</head>
<body>
<div id="app">
<h1>{{title}}</h1>
<mycomponent></mycomponent>
</div>
<script>
Vue.component('mycomponent',{
template: '<div><el-popover placement="top-start" title="标题" width="200" trigger="hover" content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"> <el-button slot="reference">hover 激活</el-button></el-popover> <el-button @click="click">点击测试</el-button></div>',
data () {
return {
message: 'hello world'
}
},
mounted(){
console.log("自动加载")
console.log(this.message)
// console.log(app.title)
},
methods:{
click(){
console.log("点击测试")
console.log(app.title)
}
}
})
var app = new Vue({
el: '#app',
data: {
title:'主标题'
},
})
</script>
</body>
</html>
代码如上:
1、new Vue定义为app
2、data有title值为“主标题”
3、mycomponent组件click方法执行的话,console.log(app.title)可以运行
4、mycomponent组件mounted执行的话,console.log(app.title)就会报错
求解答?谢谢
主要原因是因为你在mounted中调用了app,而此时app对象尚未形成,Vue.component()执行在new Vue()之前。根据规范,组件注册理应在Vue实例创建之前,因为在new Vue()中你可能会用到刚刚创建的组件,所以一定要先创建后使用。
如果你非要在mounted中调用的话,那就只能使用setTimeout,将即将执行的代码加入到队列中。