props(父传子)和自定义事件(子传父)

组件基础

被引用的子组件:

<template>
	<div>
		<h3>组件</h3>
	</div>
</template>

<script>
	export default {
		name: "mycomponent",
	}
</script>
<!-- scoped:代表当前样式,只在当前组件中生效 -->
<style scoped>
	h3{
		color: rebeccapurple;
	}
</style>

父组件:

<template>
	<!-- 第三步:以标签的形式加载组件 -->
	<mycomponent></mycomponent>
</template>

<script>
	/* 第一步:导入组件 */
	import mycomponent from './components/mycomponent.vue'
	export default {
		// 第二步:挂载组件
		components: {
			mycomponent
		}
	}
</script>

props【父传子】(组件数据传递)

父组件

<template>
	<!-- 第一步:动态数据传递 -->
	<mycomponent :title="title" :names="names"></mycomponent>
</template>
<script>
	import mycomponent from './components/mycomponent.vue'
	export default {
		data() {
			return{
				title:"标题",
				names:["11","22"]
			}
		},
		components: {
			mycomponent
		}
	}
</script>

子组件

<template>
	<div>
		<!-- 第三步:直接引用 -->
		<h3>{{title}}</h3>
		<ul>
			<li v-for="(item,index) in names" :key="index">{{item}}</li>
		</ul>
	</div>
</template>
<script>
	export default {
		name: "mycomponent",
		//第二步:接收值
		props:{
			title:{
				type:String,
				default:""
			},
			//数组和对象必须以函数形式返回
			names:{
				type:Array,
				default:function(){
					return []
				}
			}
		}
	}
</script>

type的类型:

  • String 字符串
  • Number 数字
  • Boolean 布尔
  • Array 数组
  • Object 对象
  • Date 日期
  • Function 函数
  • Symbol 独一无二的值

自定义事件【子传父】(组件数据传递)

父组件

<template>
	<!-- 自定义的事件名称为(参数1),自定义方法不加括号 -->
	<mycomponent @onEvent="getData"></mycomponent>
</template>
<script>
	import mycomponent from './components/mycomponent.vue'
	export default {
		methods:{
			// 自定义带data方法来获取传值
			getData(data){
				console.log(data)
			}
		},
		components: {
			mycomponent
		}
	}
</script>

子组件

<template>
	<div>
		<!-- 引用方法 -->
		<button @click="senddata()">传递</button>
	</div>
</template>
<script>
	export default {
		name: "mycomponent",
		data() {
			return {
				title: "标题",
			}
		},
		methods:{
			// 在方法里面传参
			senddata(){
				//参数1:字符串(理论上是随意的,但是需要有意义【因为会被父组件引用】)
				//参数2:传递的参数
				this.$emit("onEvent",this.title)
			}
		}
	}
</script>
<!-- scoped:代表当前样式,只在当前组件中生效 -->
<style scoped>
	h3 {
		color: rebeccapurple;
	}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值