vue组件之间的通信方式

组件之间的通信方式有很多种 这里分享4种组件之间的通信方式

props(主要是父传子)  自定义事件(主要是子传父)  pubsub消息订阅与发布  xuex

1.props和自定义事件

app.vue里面的代码

<template>
  <div id="app">
	<!-- 第三步,渲染组件到页面上 并传参 -->
	<props name="程连杰" age="22"/>
	<emit @del2="del3"/> 
     <p ref="word" class="word" >我是即将被删除的</p>
  </div>
</template>
<script>
// 1.第一步引入组件
import props from './components/Props'
import emit from './components/Emit'
export default {
  name: 'app',
  //2.第二步,挂载组件
  components: {
	props,
	emit
  },
  methods:{
	  del3(){
		  this.$refs.word.remove();
	  }
  }
}
</script>
<style scoped>
</style>

 Props里面的代码

<template>
	<div>
		<p>{{name}}</p>
		<p>{{age}}</p>
	</div>
</template>
<script>
	export default{
		name:"Props",
		// 接收父组件传参
		props:['name','age']
	}
</script>
<style scoped>
</style>

 Emit里面的代码

<template>
	<button @click="del">删除</button>
</template>

<script>
	export default{
		name:"Emit",
		methods:{
			del(){
				this.$emit("del2")
			}
				
		}
	}
</script>

<style>
</style>

 pubsub消息订阅与发布

posted @ 2019-12-09 19:17  程小杰呀  阅读(195)  评论(0编辑  收藏  举报