Iwen's blog Iwen's blog
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于

Iwen

不摸鱼的哥哥
首页
  • 前端文章

    • JavaScript
    • Vue
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 小程序笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • Linux
  • 学习
  • 面试
  • 心情杂货
  • 友情链接
  • 网站
  • 资源
  • Vue资源
  • 分类
  • 标签
  • 归档
复盘
关于
  • Vue

  • Vue进阶

    • 组件通信
      • props/$emit
        • 父组件向子组件传值
        • 子组件向父组件传值
      • $children / $parent
      • provide/ inject
      • ref/refs
      • eventBus
      • Vuex
      • $attrs与 $listeners
      • 总结
    • event
    • Vue3响应式原理
    • Vue3 Composition API
    • v-for中的key作用
    • vue-router传参方式
  • CSS

  • ES6

  • Base

  • Core

  • Array

  • Object

  • String

  • Async

  • Browser

  • Http

  • 性能优化

  • 正则

  • 经典总结

  • 设计模式

  • 数据结构

  • 算法

  • 手写

  • TypeScript

  • 复盘
  • Vue进阶
Mr.w
2020-11-29

组件通信

# 组件通信

# props/$emit

父组件通过props的方式向子组件传递数据,而通过$emit子组件可以向父组件通信。

# 父组件向子组件传值

下面通过一个例子说明父组件如何向子组件传递数据:在子组件中如何获取父组件中的数据list: ['libai', 'tianzhen', 'hahaha']

// 父组件
<template>
	<div class="home">
		<div v-for="(item, index) in list" :key="index">{{item}}</div>
		<children1 :message="list"></children1>
	</div>
</template>

<script>
import children1 from '@/components/children1.vue'
export default {
    name: 'Home',
	components: { children1 },
	data(){
		return{
			list: ['libai', 'tianzhen', 'hahaha']
		}
	}
}
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 子组件 1
<template>
    <div>
		<div v-for="(item, index) in message" :key="index">{{item}}</div>
    </div>
</template>

<script>
export default {
    props: ['message']
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12

# 子组件向父组件传值

$emit绑定一个自定义事件, 当这个语句被执行时, 就会将参数arg传递给父组件, 父组件通过v-on监听并接收参数。

// 父组件
<template>
	<div class="home">
		<div v-for="(item, index) in list" :key="index">{{item}}</div>
		<children1 :message="list" @onEmitIndex="onEmitIndex"></children1>
		<p>{{currentIndex}}</p>
	</div>
</template>

<script>
import children1 from '@/components/children1.vue'
export default {
    name: 'Home',
	components: { children1 },
	data(){
		return{
			currentIndex: -1,
			list: ['libai', 'tianzhen', 'hahaha']
		}
	},
	methods: {
		onEmitIndex(idx) {
			console.log(idx)
			this.currentIndex = idx
		}
	}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
    <div>
		<div v-for="(item, index) in message" :key="index" @click="emitIndex(index)">{{item}}</div>
    </div>
</template>

<script>
export default {
    props: ['message'],
    methods: {
        emitIndex(index) {
            this.$emit('onEmitIndex', index)
        }
    }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# $children / $parent

通过$parent和$children就可以访问组件的实例,拿到实例代表什么?代表可以访问此组件的所有方法和data。接下来就是怎么实现拿到指定组件的实例。

// 父组件
<template>
	<div class="home">
		<div v-for="(item, index) in list" :key="index">{{item}}</div>
		<children1 :message="list" @onEmitIndex="onEmitIndex"></children1>
		<p>{{currentIndex}}</p>
		<button @click="btn">获取子组件</button>
	</div>
</template>
<script>
import children1 from '@/components/children1.vue'
export default {
    name: 'Home',
	components: { children1 },
	data(){
		return{
			currentIndex: -1,
			list: ['libai', 'tianzhen', 'hahaha']
		}
	},
	methods: {
		onEmitIndex(idx) {
			console.log(idx)
			this.currentIndex = idx;
		},
		btn(){
			this.$children[0].message;
			this.$children[0].btn()
			this.$children[0].name = 33;
		}
	}
}
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 子组件
<template>
    <div>
		<div v-for="(item, index) in message" :key="index" @click="emitIndex(index)">{{item}}</div>
        <p>{{name}}</p>
        <button @click="btn">获取父组件</button>
    </div>
</template>
<script>
export default {
    props: ['message'],
    data (){
        return {
            name: 2
        }
    },
    methods: {
        emitIndex(index) {
            this.$emit('onEmitIndex', index)
        },
        btn(){
            console.log(this.$parent.currentIndex)
            console.log(this.$parent.list)
        }
    }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

要注意边界情况,如在#app上拿$parent得到的是new Vue()的实例,在这实例上再拿$parent得到的是undefined,而在最底层的子组件拿$children是个空数组。 也要注意得到$parent和$children的值不一样,$children的值是数组,而$parent是个对象

上面两种方式用于父子组件之间的通信, 而使用props进行父子组件通信更加普遍; 二者皆不能用于非父子组件之间的通信。

# provide/ inject

provide/inject是vue2.2.0新增的api, 简单来说就是父组件中通过provide来提供变量, 然后再子组件中通过inject来注入变量。

注意: 这里不论子组件嵌套有多深, 只要调用了inject那么就可以注入provide中的数据,而不局限于只能从当前父组件的props属性中回去数据

举例验证

接下来就用一个例子来验证上面的描述: 假设有三个组件: A.vue、B.vue、C.vue 其中 C是B的子组件,B是A的子组件

// A.vue
<template>
  <div>
	<comB></comB>
  </div>
</template>
<script>
  import comB from '../components/test/comB.vue'
  export default {
    name: "A",
    provide: {
      for: "demo"
    },
    components:{
      comB
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// B.vue
<template>
  <div>
    {{demo}}
    <comC></comC>
  </div>
</template>
<script>
  import comC from '../components/test/comC.vue'
  export default {
    name: "B",
    inject: ['for'],
    data() {
      return {
        demo: this.for
      }
    },
    components: {
      comC
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// C.vue
<template>
  <div>
    {{demo}}
  </div>
</template>
<script>
  export default {
    name: "C",
    inject: ['for'],
    data() {
      return {
        demo: this.for
      }
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# ref/refs

ref:如果在普通的DOM元素上使用,引用指向的就是DOM元素;

如果用在子组件上,引用就指向组件实例,可以通过实例直接调用组件的方法或访问数据, 我们看一个ref来访问组件的例子:

// 父组件
<template>
	<component-a ref="comA"></component-a>
</template>
<script>
export default {
	mounted () {
		const comA = this.$refs.comA;
		console.log(comA.name);  // Vue.js
		comA.sayHello();  // hello
	}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
// 子组件不用动
<script>
export default {
	data () {
		return {
		name: 'Vue.js'
		}
	},
	methods: {
		sayHello () {
			console.log('hello')
		}
  	}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# eventBus

eventBus又称为事件总线,在vue中可以使用它来作为沟通桥梁的概念, 就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件, 所以组件都可以通知其他组件。

eventBus也有不方便之处, 当项目较大,就容易造成难以维护的灾难

  1. 初始化

首先需要创建一个事件总线并将其导出, 以便其他模块可以使用或者监听它.

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
1
2
3
  1. 发送事件

假设你有两个组件: additionNum和showNum, 这两个组件可以是兄弟组件也可以是父子组件;这里我们以兄弟组件为例:

  1. 接收事件

  2. 移除事件监听者

# Vuex

// 父组件
<template>
  <div id="app">
    <ChildA/>
    <ChildB/>
  </div>
</template>
<script>
  import ChildA from './components/ChildA' // 导入A组件
  import ChildB from './components/ChildB' // 导入B组件

  export default {
    name: 'App',
    components: {ChildA, ChildB} // 注册A、B组件
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 子组件childA
<template>
  <div id="childA">
    <h1>我是A组件</h1>
    <button @click="transform">点我让B组件接收到数据</button>
    <p>因为你点了B,所以我的信息发生了变化:{{BMessage}}</p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        AMessage: 'Hello,B组件,我是A组件'
      }
    },
    computed: {
      BMessage() {
        // 这里存储从store里获取的B组件的数据
        return this.$store.state.BMsg
      }
    },
    methods: {
      transform() {
        // 触发receiveAMsg,将A组件的数据存放到store里去
        this.$store.commit('receiveAMsg', {
          AMsg: this.AMessage
        })
      }
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 子组件 childB
<template>
  <div id="childB">
    <h1>我是B组件</h1>
    <button @click="transform">点我让A组件接收到数据</button>
    <p>因为你点了A,所以我的信息发生了变化:{{AMessage}}</p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        BMessage: 'Hello,A组件,我是B组件'
      }
    },
    computed: {
      AMessage() {
        // 这里存储从store里获取的A组件的数据
        return this.$store.state.AMsg
      }
    },
    methods: {
      transform() {
        // 触发receiveBMsg,将B组件的数据存放到store里去
        this.$store.commit('receiveBMsg', {
          BMsg: this.BMessage
        })
      }
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

vuex的store,js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
  // 初始化A和B组件的数据,等待获取
  AMsg: '',
  BMsg: ''
}

const mutations = {
  receiveAMsg(state, payload) {
    // 将A组件的数据存放于state
    state.AMsg = payload.AMsg
  },
  receiveBMsg(state, payload) {
    // 将B组件的数据存放于state
    state.BMsg = payload.BMsg
  }
}
export default new Vuex.Store({
  state,
  mutations
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# $attrs与 $listeners

现在我们来讨论一种情况, 我们一开始给出的组件关系图中A组件与D组件是隔代关系, 那它们之前进行通信有哪些方式呢?

  1. 使用props绑定来进行一级一级的信息传递, 如果D组件中状态改变需要传递数据给A, 使用事件系统一级级往上传递
  2. 使用eventBus,这种情况下还是比较适合使用, 但是碰到多人合作开发时, 代码维护性较低, 可读性也低
  3. 使用Vuex来进行数据管理, 但是如果仅仅是传递数据, 而不做中间处理,使用Vuex处理感觉有点大材小用了.

在vue2.4中,为了解决该需求,引入了$attrs和$listeners, 新增了inheritAttrs选项。

在版本2.4以前,默认情况下,父作用域中不作为prop被识别 (且获取) 的特性绑定 (class 和 style 除外),将会“回退”且作为普通的HTML特性应用在子组件的根元素上。接下来看一个跨级通信的例子:

// app.vue
// index.vue
<template>
  <div>
    <child-com1
      :name="name"
      :age="age"
      :gender="gender"
      :height="height"
      title="程序员成长指北"
    ></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      name: "zhang",
      age: "18",
      gender: "女",
      height: "158"
    };
  }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// childCom1.vue
<template class="border">
  <div>
    <p>name: {{ name}}</p>
    <p>childCom1的$attrs: {{ $attrs }}</p>
    <child-com2 v-bind="$attrs"></child-com2>
  </div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
  components: {
    childCom2
  },
  inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性
  props: {
    name: String // name作为props属性绑定
  },
  created() {
    console.log(this.$attrs);
     // { "age": "18", "gender": "女", "height": "158", "title": "程序员成长指北" }
  }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// childCom2.vue
<template>
  <div class="border">
    <p>age: {{ age}}</p>
    <p>childCom2: {{ $attrs }}</p>
  </div>
</template>
<script>

export default {
  inheritAttrs: false,
  props: {
    age: String
  },
  created() {
    console.log(this.$attrs); 
    // { "gender": "女", "height": "158", "title": "程序员成长指北" }
  }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 总结

常见使用场景可以分为三类:

  1. 父子组件通信: props,$parent / $children,provide / inject,ref,$attrs / $listeners
  2. 兄弟组件通信: eventBus,vuex
  3. 跨级通信: eventBus;Vuex;provide / inject、$attrs / $listeners
一句话说明
event

← 一句话说明 event→

最近更新
01
flex布局页面自适应滚动条问题
12-28
02
前后端分离开发请求接口跨域如何携带cookie的问题
12-28
03
怎么实现div长宽比固定width-height4比3
12-28
更多文章>
Theme by Vdoing | Copyright © 2017-2022 Iwen | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式