父子组件之间的传值
第一种方式:props和$emit
父组件通过props向子组件传递数据,子组件通过$emit向父组件传递数据
父组件向子组件传递
// 父组件
<template>
<div id="father">
<son :msg="msgData" :fn="myFunction"></son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
name: father,
data() {
msgData: "父组件数据";
},
methods: {
myFunction() {
console.log("vue");
}
},
components: {
son
}
};
</script>
// 子组件
<template>
<div id="son">
<p>{{msg}}</p>
<button @click="fn">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: ["msg", "fn"]
};
</script>
子组件向父组件
子组件通过$emit向父组件传递,父组件通过v-on监听并接收参数。
// 父组件
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{{currentIndex}}</p>
</div>
</template>
<script>
import comArticle from './test/article.vue'
export default {
name: 'comArticle',
components: { comArticle },
data() {
return {
currentIndex: -1,
articleList: ['红楼梦', '西游记', '三国演义']
}
},
methods: {
onEmitIndex(idx) {
this.currentIndex = idx
}
}
}
</script>
//子组件
<template>
<div>
<div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
</div>
</template>
<script>
export default {
props: ['articles'],
methods: {
emitIndex(index) {
this.$emit('onEmitIndex', index) // 触发父组件的方法,并传递参数index
}
}
}
</script>
第二种方式:ref和$refs 父组件拿子组件 $$parent子组件拿父组件的值
为什么要这两个方式结合,因为$$children方式通过父组件拿取子组件的方式属于非响应式。所以这两者使用会好一点。
ref属性用在子组件上,这个引用指向子组件的实例。通过这个实例来访问子组件的方法和数据。
//子组件
export default {
data () {
return {
name: 'JavaScript'
}
},
methods: {
sayHello () {
console.log('hello')
}
}
}
//父组件
<template>
<child ref="child"></component-a>
</template>
<script>
import child from './child.vue'
export default {
components: { child },
mounted () {
console.log(this.$refs.child.name); // JavaScript
this.$refs.child.sayHello(); // hello
}
}
</script>
第三种方式:依赖注入:project/inject 是嵌套层级关系,不仅仅是单纯的父子关系
project,inject是vue提供的两个钩子,和data属于一个等级。
project的写法和data一样。
project发送
inject接收
//父组件
provide() {
return {
num: this.num
};
}
//子组件
inject: ['num']
注意:依赖注入所获取到的值是非响应式的
兄弟组件之间的传值
第一种方式:eventBus(适用于任意组件之间的传值方式)
步骤:
(1)创建事件中心(来管理组件之间的通信):
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
(2)发送事件
用on接受
假设我们有两个兄弟组件firstCom,secondCom。
<template>
<div>
<first-com></first-com>
<second-com></second-com>
</div>
</template>
<script>
import firstCom from './firstCom.vue'
import secondCom from './secondCom.vue'
export default {
components: { firstCom, secondCom }
}
</script>
在firstCom中发送事件
<template>
<div>
<button @click="add">加法</button>
</div>
</template>
<script>
import {EventBus} from './event-bus.js' // 引入事件中心
export default {
data(){
return{
num:0
}
},
methods:{
add(){
EventBus.$emit('addition', {
num:this.num++
})
}
}
}
</script>
在seconed中接收事件
<template>
<div>求和: {{count}}</div>
</template>
<script>
import { EventBus } from './event-bus.js'
export default {
data() {
return {
count: 0
}
},
mounted() {
EventBus.$on('addition', param => {
this.count = this.count + param.num;
})
}
}
</script>