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