父子组件,非父子组件传值(组件传值必看!)

一:

父组件向子组件传值:
father:

<template>
	<father>
	    <son :message="msg"></son> (message动态绑定msg数据,必须v-bind:动态绑定)
	</father>
</template>
<script>
export default {
	data(){
	    return {
	        msg: "父亲"
	    }
	}
}
</script>

son:

<template>
	<div>
	    <p>{{message}}</p>
	</div>
</template>

<script>
export default {
	props:["message"]
	data(){
		return {}
	}
	</script>
}	

或者

props: {
    message: {
        type: String,                 //类型为字符串
        default:"默认值"     //可设置默认值
    }
}

props: {
message: {
type: Array, //类型为数组
default: [‘f’,‘a’,‘z’] //默认值
}
}

二:

子组件向父组件传值
因为vue中子组件不能更改父组件中的内容,因此通过子组件触发一些事件来传值给父组件。

son:

<template>
   <button @click ='setValue'>点击</button>
</template>
<script>
export default {
	data(){
	  return {
	    value: "儿子"
	  }
	},
	methods:{
	  setValue:function(){ 
	    this.$emit('sendValue',this.value); //this.value为向父组件传递的数据
	  }
	}
}	
</script>

parent:

<template>
	<div id="app">
	    <son @sendValue="receive"></son> //监听由子组件触发的 'sendValue'事件,然后调用receive方法来更改数据
	    <p>{{value}}</p>
	</div>
</template>
<script>
export default {
	data(){
	  return{
	  	value:"father"
	  }
	},
	methods: {
	  receive:function(val) {
	    this.value = val;
	  }
	}
}	
</script>

三:

非父子组件之间的通讯
有时候两个非父子关系组件也需要通信 。通常,使用一个空的 Vue 实例作为中央事件总线,类似于一个“中转站”,进行发送和接收数据。

commonEvent.js

import Vue from ‘vue’
var station = new Vue() //创建事件"中转站"
export default station

或者

import Vue from ‘vue’
export default new Vue

X.vue

<template>
	<button @click="bClick">content</button >
</template>
// 触发组件X中的事件
<script>
import eventdata from './commonEvent.js' (这个路径看你的commonEvent.js文件放哪里)
export default {
	methods: {
	    bClick(){
	        eventdata .$emit('send',this.message);  
	    }
	}
}	
</script>

Y.vue
// 在组件Y监听事件

<template>
    < div>{{message}}< /div>
</template>

<script>
import eventdata from './commonEvent.js'
export default {
	data(){
	   return{
	      message:"默认值"
	   }
	}
}	
</script>

(调用created钩子函数进行监听事件的初始化)
created() {
eventdata .$on(‘send’, function(val){ //接收事件
this.message = val
})
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值