完整代码:Github
一、父子组件通信:props 和 $emit
- 父组件向子组件传值:
props
(1)父组件发送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' } ] } })
<div id="app"> <blog-post v-for="post in posts" :key="post.id" :title="post.title" content="固定传值"></blog-post> </div>
(2)子组件接收
Vue.component("blog-post", { props: ['title', 'content'], template: ` <div> <h3>{{ title }}</h3> <p>{{ content }}</p> </div> `, })
- 子组件向父组件传值:
$emit
(1)子组件发送Vue.component("blog-post", { data(){ return { title: "I am from blog-post" } }, template: ` <div> <button @click="change">传值</button> </div> `, methods: { change(){ this.$emit("changed", this.title) } } })
(2)父组件接收
<div id="app"> <blog-post @changed="update"></blog-post> <h2>{{ app_title }}</h2> </div>
new Vue({ el: '#app', data: { app_title: '', }, methods: { update(str){ this.app_title = str; } } })
二、兄弟组件通信:$on 和 $emit(
中央事件总线: 一个空的 Vue 实例
)注:该方法可实现父子、兄弟、隔代组件之间的通信
(1)定义中央事件总线
var Bus = new Vue();
(2)注册组件
① 组件A<template id="a"> <div> <h1>A组件</h1> <h3>我的名字是: {{ name }}</h3> <h3>我的年龄是: {{ age }}</h3> <button @click="send">将数据发送给C组件</button> </div> </template>
var A = { template: '#a', data(){ return { name: 'tom', age: '' } }, methods: { send(){ Bus.$emit('data-a', this.name); } }, mounted(){ Bus.$on('data-c', age => { this.age = age }) } }
② 组件B
<template id="b"> <div> <h1>B组件</h1> <h3>我的年龄是: {{ age }}</h3> <button @click="send">将数据发送给C组件</button> </div> </template>
var B = { template: '#b', data(){ return { age: 20 } }, methods: { send(){ Bus.$emit('data-b', this.age); } }
③ 组件C
<template id="c"> <div> <h3>C组件: {{ name }}, {{ age }}</h3> <button @click="send">将数据发送给A组件</button> </div> </template>
var C = { template: '#c', data(){ return { name: '', age: '' } }, methods: { send(){ Bus.$emit('data-c', this.age); } }, mounted(){ Bus.$on('data-a', name => { this.name = name; }) Bus.$on('data-b', age => { this.age = age; }) } }
(3)使用组件
<div id="app"> <my-a></my-a> <my-b></my-b> <my-c></my-c> </div>
var app = new Vue({ el: '#app', components: { 'my-a': A, 'my-b': B, 'my-c': C, } })
三、隔代组件:$attrs 和 $listeners
(未完待续)