Vue.js——实现vue组件之间的通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012194956/article/details/79508119

1.父组件->子组件

<div id="app">
	<son :message="msg"></son>
</div>

<script>
	//创建一个vue实例
	const app=new Vue({
		el:"#app",
		data:{
			msg:"我是父组件的数据"
		}
	});

	//注册一个组件,取名为son
	Vue.componet(
		'son',
		{
			props:['message'],
			template:'<div></div>'
		}
		);
</script>
  • Vue实例app中含有数据msg值为“我是父组件的数据”,它将会传递给子组件son。
  • 通过Vue.component()来注册一个组件,组件取名为son。
  • 以上,父组件和子组件都准备好了,开始传递数据,父组件向子组件传递参数。prop选项声明了它要接受的参数是message,而接收到的对应值是父组件中的数据msg。

需要注意的是,props是单向绑定(父->子),是vue为了防止子组件无意修改父组件的数据和状态。

2.子组件->父组件

相较于父组件->子组件,这里会复杂一点,需要用到自定义事件。

每个vue实例都实现了事件接口,我们可以用它们提供的API $emit(eventName)来触发一个事件。

<div id="app">
	<son @connect="say"></son>
</div>
<script>
	const app=new Vue({
		el:"#app",
		methods:{
			say(msg){
				console.log(msg);
			}
		}
	});

	Vue.component(
		'son',
		{
			template:'<button @click="send">点击</button>',
			data(){
				return{
					msg:'大家好,我是子组件的数据'
				}
			},
			methods:{
				send(){
					this.$emit('connect',this.msg);
				}
			}
		});
</script>

注册一个组件,就是一个按钮button,点击它的时候,会触发组件内部的send()方法,而方法里面会触发一个事件,取名为connect。

然后我们在父组件用v-on(可缩写为@)监听这个事件connect。

我们设置了事件connect触发的处理程序是一个say()方法,其参数是子组件的data中的msg。

3.非父子组件通信

猜你喜欢

转载自blog.csdn.net/u012194956/article/details/79508119