1. 父向子组件传值
-
先在父组件给子组件自定义属性绑定一个定义变量
<template class="father">
<child :自定义属性名="父组件的变量"></child>
<template >
- 在子组件中使用 props 接收这个变量 用法和data中的变量相同,但值来源不同
export default {
name: "child",
props: ["自定义属性名"],
data() {}
}
2. 子向父组件传值
-
先在父组件中给子组件的 自定义属性 绑定一个父组件的函数
<template class="father">
<child @自定义事件="父的处理函数">
<template >
export default {
name: "father",
data() {}
methods:{
父的处理函数(参数){
//参数:得到子组件触发事件($emit)时,传递过来的数据
}
}
})
- 在子组件使用
this.$emit('父处理函数',数据)触发父组件函数 传递参数
兄弟组价的传值
- 创建一个全局的vue实例
import Vue from 'vue';
const eventBus= new Vue() //创建事件总线
export default eventBus;
- 在具体组件引入 eventBus
import eventBus from '@u/eventBus'
eventBus.$emit('send',‘hello')
- 在需要数据的组件引入 eventBus 接收组件值
import eventBus from '@u/eventBus'
eventBus.$on('send', msg => {
console.log(msg) //控制台输出 hello
}