子組件
props: {
'seedId':String,? //接收父組件的值背稼,定義(允許)傳過來的值得類型,seedId為變量玻蝌,可直接使用
},
data() {
return {
? ? msg:“554”
};
},
methods: {
hledClose(){
this.$emit('agreement', this.msg) //給父組件傳值
console.log(this.$parent.msg)//讀取父組件數(shù)據(jù)
}
}
父組件
<check-in :seedId="seedId" @agreement="agreement"></check-in> //渲染子組件的內容 蟹肘,seedId為要傳給子組件的值,agreement為子組件傳過來的值
import checkIn from? './agreement4';//引入子組件
data:(){
? ? retrue(){
? ? ? ? seedId:'1'//定義的變量俯树,可直接把該變量傳給子組件
? ? ? ? msg:'123'
? ? }
}
created(){
? ? this.$on("agreement",(msg)=>{//可監(jiān)聽子組件通過$emit傳過來的方法
? ? ? ? this.msg=msg
? ? })
}
components:{//注冊子組件
checkIn
},
metods:{
agreement(agreement){//接收子組件的值
this.seedId = '';
}
}
非父子組件傳值(非父子組件之間的通信帘腹,必須要有公共的實例,比如js(可以是空的)许饿,才能使用?$emit?獲取?$on?的數(shù)據(jù)參數(shù)阳欲,實現(xiàn)組件通信?)
第一個組件
import Bus from '../bus.js';
export default {
? name: 'first',
? data () {
? ? return {
? ? ? value: '我來自first.vue組件!'
? ? }
? },
? methods:{
? ? add(){// 定義add方法,并將msg通過txt傳給second組件
? ? ? Bus.$emit('txt',this.value);
? ? }
? }
}
第二個組件
import Bus from '../bus.js';
export default {
? name: 'second',
? data () {
? ? return {
? ? }
? },
? mounted:function(){
? ? Bus.$on('txt',function(val){//監(jiān)聽first組件的txt事件
? ? ? console.log(val);
? ? });
? }
}
注:兩個組件引入的js必須要相同的一個js