效果图
点击大家弹
点击自己弹
并且在检查当中会有个报错
HTML
<!DOCTYPE html>
<html lang="zh-cn">
<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>
<!-- Vue 全局及局部组件 -->
<div id="app1">
<alerts></alerts>
<alert></alert>
</div>
<br>
<div id="app2">
<alerts></alerts>
<alert></alert>
</div>
<!-- 定义组件还可以定义在此处,只要在js中 template:#'idalert',
<template id="idalert">
<button @click="on_click">id大家弹</button>
</template>
-->
<script src="vue.js"></script>
<script src="main.js"></script>
</body>
</html>
JS
//全局
Vue.component('alerts',{
template:'<button @click="on_click">大家弹</button>',
methods:{
on_click:function(){
alert('全局组件大家弹!!!');
}
}
});
//封装组件
var alert_component={
//template:#'idalert',//前提时html中定义了id为idalert的template
template:'<button @click="on_click">自己弹</button>',
methods:{
on_click:function(){
alert('局部组件自己弹!!!');
}
}
};
new Vue({
el:'#app1',
components:{
//封装
alert:alert_component
//或者直接写在这里也是局部变量
/*
alert:{
template:'<button @click="on_click">自己弹</button>',
methods:{
on_click:function(){
alert('局部组件自己弹!!!');
}
}
}
*/
}
})
new Vue({
el:'#app2'
})