一、 父组件向子组件通信
1. prop 传递数据
我们用的最多方式,可以通过 Prop 向子组件传递数据。
用一个形象的比喻来说,父子组件之间的数据传递相当于自上而下的下水管子,只能从上往下流,不能逆流。这也正是 Vue 的设计理念之单向数据流。而 Prop 正是管道和管道之间的一个衔接口,这样(水)数据才能向下流.
// parent.vue
<template>
<div>
<Child :name="name" />
</div>
</template>
<script>
import Child from '@/components/child'
export default {
components: {
Child
},
data() {
return {
name: '顾鸟'
}
}
}
</script>
// child.vue
<template>
<div>{{ name }}</div>
</template>
<script>
export default {
props: {
name: {
type: String,
default: ''
}
}
}
</script>
2. $refs 获取子组件实例,进而调用子组件方法或者直接修改子组件属性
调用子组件的方法 this.$refs.child.fromParent(‘我从父组件传递过来’)
直接修改子组件的 data 数据 this.$refs.child.message2 = ‘啦啦啦’
// child.vue
<template>
<div id="child">
<div>{{ message1 }}</div>
<div>{{ message2 }}</div>
</div>
</template>
<script>
export default {
name: 'child',
data() {
return {
message1: '',
message2: ''
}
},
methods: {
fromParent(msg) {
this.message1 = msg
}
}
}
</script>
// parent.vue
<template>
<div id="parent">
<button @click="toChild">click</button>
<child ref="child"></child>
</div>
</template>
<script>
import child from '@/components/child.vue'
export default {
name: 'parent',
components: { child },
methods: {
toChild() {
this.$refs.child.fromParent('我从父组件传递过来')
this.$refs.child.message2 = '啦啦啦'
}
}
}
</script>
二、子组件向父组件通信
1. $emit 触发父组件的方法或传递数据
通过 $emit 进行触发,第一个参数为父组件监听的事件名,后续参数为父组件方法的参数
// child.vue
<template>
<div id="child">
<button @click="tryToParent">click</button>
</div>
</template>
<script>
export default {
name: 'child',
methods: {
tryToParent() {
this.$emit('toParent', '我从子组件传来')
}
}
}
</script>
// parent.vue
<template>
<div id="parent">
<child @toParent="fromChild"></child>
</div>
</template>
<script>
import child from '@/components/child.vue'
export default {
name: 'parent',
components: { child },
methods: {
fromChild(msg) {
console.log(msg)
}
}
}
</script>
三、其他方法
-
官方推荐,Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,适合处理复杂项目。
-
a t t r s 、 attrs、 attrs、listeners
a t t r s 和 attrs和 attrs 和 listeners 属性像两个收纳箱,一个负责收纳属性,一个负责收纳事件,都是以对象的形式来保存数据
-
这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。如果你熟悉 React,这与 React 的上下文特性很相似。
provide 和 inject 主要为高阶插件/组件库提供用例。并不推荐直接用于应用程序代码中。
不忘初心
参考链接:
https://www.cnblogs.com/vickylinj/p/10877765.html
https://blog.csdn.net/qq_37288477/article/details/86630428
https://www.cnblogs.com/yangshifu/archive/2018/08/22/9518528.html