父子通信:
1.父传子props
官网demo:https://cn.vuejs.org/v2/guide/components.html#%E9%80%9A%E8%BF%87-Prop-%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E9%80%92%E6%95%B0%E6%8D%AE
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="app"> <counter name='1' count='2'></counter> <blog-post title="My journey with Vue"></blog-post> <blog-post title="Blogging with Vue"></blog-post> <blog-post title="Why Vue is so fun"></blog-post> <blog-post v-for="post in posts" v-bind:title="post.title"></blog-post> </div> <script src="js/vue.js"></script> <script src="js/main.js"></script> </body> </html>
Vue.component('counter',{ template:`<div>
<input v-model="username" />{{username}}
<button v-on:click='add'>点击{{counter}}</button>
</div>`, props:['name','count'], data:function(){ return { username:this.name, counter:this.count } }, methods:{ add:function(){ this.counter++; console.log(this.counter) } } }) Vue.component('blog-post', { props: ['title'], template: '<h3>{{ title }}</h3>' }) new Vue({ el:'#app', data:{ posts: [ { id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' } ] } })
通过props实现父到子传递
2.子传父
兄弟组件通信: