Components basis - global components
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app1">
<!-- 3. 既可以在根组件 app2 的模板中使用 GlobalComponent 组件 -->
<global-component></global-component>
</div>
<div id="app2">
<!-- 4. 也可以在根组件 app2 的模板中使用 GlobalComponent 组件 -->
<global-component></global-component>
</div>
<script src="./vue.js"></script>
<script>
// 组件是可以重复使用的,每次使用时,Vue 都会帮我们创建一个该组件的实例。
// new GlobalComponent()
// new GlobalComponent()
// 1. 使用 Vue.extend() 方法创建一个组件的构造函数,该构造函数继承了 Vue,(也就是说,我们创建的构造函数是 Vue 的子类)
const GlobalComponent = Vue.extend({
data: function () {
return {
message: '全局组件的数据'
}
},
template: '<div><h1>{{message}}</h1></div>'
});
// 2. 将 GlobalComponent 组件注册成全局组件
Vue.component('global-component', GlobalComponent)
const app1 = new Vue({
el: '#app1',
data: {
message: 'app1根组件的数据'
}
});
const app2 = new Vue({
el: '#app2',
data: {
message: 'app2根组件的数据'
}
});
</script>
</body>
</html>
Shorthand global components
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 3. 使用 GlobalComponent 组件 -->
<global-component></global-component>
<global-component></global-component>
</div>
<script src="./vue.js"></script>
<script>
// 简写之前:
// const GlobalComponent = Vue.extend({
// data: function () {
// return {
// message: '全局组件的数据'
// }
// },
// template: '<div><h1>{{message}}</h1></div>'
// });
// Vue.component('global-component', GlobalComponent)
// 简写方式一:
// Vue.component('global-component', Vue.extend({
// data: function () {
// return {
// message: '全局组件的数据'
// }
// },
// template: '<div><h1>{{message}}</h1></div>'
// }))
// 简写方式二:只需要将 Vue.extend() 方法中的对象作为 Vue.component() 方法的第二个参数即可。
// Vue.component() 方法会在内部帮我们调用 Vue.extend() 方法
Vue.component('global-component', {
data: function () {
return {
message: '全局组件的数据'
}
},
template: '<div><h1>{{message}}</h1></div>'
})
new Vue({
el: '#app',
data: {
}
});
</script>
</body>
</html>