父子组件传值:(二种传值:一个是props,一个是refs)
1:props
(1) 父组件给子组件传值:父组件绑定动态属性 传值 / 传方法 / 传实例
<v-header
:msg="msg"
:fatherFunction="fatherFunction" //父组件传递方法时不加()
:home="this"
></v-header>
(2) 子组件通过props 接收父组件传过来的 值 / 方法 / 父亲实例
props: { msg: String, fatherFunction: Function, home: Object },
methods: {
getparent() {
console.log(this.home.msg); //获得父组件的内容
this.home.fatherFunction("我是父组件的方法"); //执行父组件的方法
},
//执行父组件方法也可直接调用;<button @click="fatherFunction">执行</button>
}
特:如果子组件和父组件传值的props和data中定义的重复则会冲突,都有的时候会用props的!!
示例:
2:refs
(1)父调用子组件的时候定义一个ref;
<v-header
:msg="msg"
:fatherFunction="fatherFunction"
:home="this"
ref="header"
></v-header>
(2)父组件主动获取子组件的数据和方法
1:调用子组件的时候定义一个ref;
2:在父组件拿到子组件的内容/方法通过
`this.$refs.header.属性
this.$refs.header.方法`
getSon() {
console.log(this.$refs.header.sonMsg); //获得子组件的数据
this.$refs.header.son(); //执行子组件的方法
},
fatherFunction(item) {
console.log("父组件的方法", item);
},
(3)子组件主动获取父组件的数据和方法
1:调用子组件的时候定义一个ref;
2:在子组件拿到父组件的内容/方法
`this.$parent.数据
this.$parent.方法`
getFather() {
console.log(this.$parent.msg);//获得父组件的数据
this.$parent.fatherFunction("调用父组件的方法");//执行父组件的方法
},
son() {
console.log("我是子组件的方法");
},
示例:
非父子组件传值:(一种传值:$emit)
1:emit
(1):新建一个js文件,例:VueEvent.js 引入vue 实例化vue 暴露这个实例
import Vue from 'vue';
var VueEvent=new Vue();//新建这个实例
export default VueEvent;//暴露这个实例
(2):在需要广播的地方引入这个实例
import VueEvent from "../model/VueEvent.js";
(3):接收发送数据:
发送: 通过VueEvent.$emit(名,数据)
VueEvent.$emit("to-home", this.msg);
接收: 通过VueEvent.$on(名,方法)
VueEvent.$on("to-home", (data) => {
console.log(data);
});
示例: