(一)父組件向子組件傳值==props
1.在父組件中使用子組件的地方綁定數據
<children :message="message"></children>
2.子組件使用props接收父組件傳過來的數據
props:{
message:String
}
3.示例:
(二)子組件向父組件傳值==$emit,也可以用來調用父組件中的方法
1.子組件直接使用$emit將內部數據傳遞給父組件
this.$emit("childByValue",this.childValue);
2.父組件中接收數據
<template> <child @childByVlaue="childByVlaue"></dhild> </template> methods:{ childByValue:function(childValue){ this.name=childValue; } }
(三)可以通過$parent和$children獲取父子組件參數
$children[i].params
this.$parent.params
(四)兄弟之間傳值===Vuex
1.在state里定義數據和屬性
state: {
userName: '',
},
2.在mutation里定義函數
mutations: {
setUserName(state, name) {
state.userName = name
},
},
3.設置值
this.$store.comit('setUserName',params)
4.獲取值
this.$store.state.user.userName
(五)父組件調用子組件的方法===ref
1.子組件的方法
methods:{
childMethod(){
alert("我是子組件的方法");
}
}
2.父組件調用子組件的方法
<template> <child ref="child"></child> <div @click="parentMethod"></div> </template> methods:{ parentMethod(){ this.$refs.child.childMethod(); } }