Component组件是可复用的 Vue实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>组件</title>
<script src="vue.js"></script>
</head>
<body>
<!-- 组件是可复用的 Vue实例,它们与 new Vue 接收相同的选项,
如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。-->
<!-- 组件之间可以相互调用方法,相互发送事件进行通信 -->
<!-- 在一个大型应用中,有必要将整个应用程序划分为组件,以使开发更易管理 -->
<!--<div id="app">
<app-nav></app-nav>
<app-view>
<app-sidebar></app-sidebar>
<app-content></app-content>
</app-view>
</div>-->
<div id="app">
<args-component ref="args" v-bind:args='{title:"标题",text:"内容"}'></args-component>
<a-component ref="a"></a-component>
<b-component ref="b"></b-component>
</div>
<script>
//传参
Vue.component('args-component',{
props:['args'],
template:'<div><p>{{args.title}}</p><p>{{args.text}}</p></div>',
created:function(){
console.log('args-component 组件初始化完成');
//调用父组件方法
console.log(this.$root.getName());
},
methods:{
getName:function(){
return '我是传参示例组件'
}
}
})
//组件间通信
Vue.component('a-component',{
template:'<button v-on:click="onclick">点击发送消息</button>',
methods:{
onclick:function(e){
this.$root.$emit('a-click','组件A被点击了')
}
}
})
Vue.component('b-component',{
data:function(){
return {
message:'准备接收组件A的消息'
}
},
template:'<p ref="b">{{message}}</p>',
mounted:function(e){
var root = this;
this.$root.$on('a-click',function(data){
root.message = data;
})
}
})
var vm = new Vue({
el:'#app',
mounted:function(){
//调用子组件方法
console.log(this.$refs.args.getName())
},
methods:{
getName:function(){
return '我是根VUE实例'
}
}
})
</script>
</body>
</html>