13-组件

组件文件夹必须为components才会出现新建组件的选项

组件的使用和注册

test组件

<template>
	<view>
		这是test组件
		这是父组件传递过来的数据{{title}}
		<button @click="sendnum">给父组件传值</button>
	</view>
</template>

<script>
	export default {
		props:['title'],
		name:"test",
		data() {
			return {
				num:3
			};
		},
		beforeCreate() {
			console.log("实例初始化之后调用")
		},
		created() {
			console.log("实例创建完成后调用")
		},
		methods:{
			sendnum(){
				this.$emit('myEven',this.num)
			}
		}
	}
</script>

<style>

</style>

在index页面导入组件 写在script中

<script>
	import test from "../../components/test.vue"
</script>

注册组件

<script>
		components:{
			// key val一样直接省略写法 组件名:组件 test:test
			test
		}
</script>

使用组件

v-if的boolean值决定组件是否显示

<template>
	<view class="content">
		<test v-if="flag" :title="title" @myEven="getNum"></test>
		<button @click="checktest">切换test组件</button>
	</view>
</template>

子组件给父组件传值

预先定义好了num

子组件

<template>
	<view>
		这是test组件
		这是父组件传递过来的数据{{title}}
		<button @click="sendnum">给父组件传值</button>
	</view>
</template>

子组件注册myEven事件 

		methods:{
			sendnum(){
				this.$emit('myEven',this.num)
			}
		}

父组件

父组件加载myEven事件

<template>
	<view class="content">
		<test v-if="flag" @myEven="getNum"></test>
		<button @click="checktest">切换test组件</button>
		子组件传递过来的数据:{{num}}
	</view>
</template>
		methods: {
			getNum(num){
				console.log(num)
				this.num=num
			}
		},

父组件给子组件传值

父组件

在组件标签绑定title参数

<template>
	<view class="content">
		<test v-if="flag" :title="title" @myEven="getNum"></test>
		<button @click="checktest">切换test组件</button>
		子组件传递过来的数据:{{num}}
	</view>
</template>
		data() {
			return {
				title: 'Hello',
				flag:true,
				num:0
			}
		},

子组件

通过props接收参数

<script>
	export default {
		props:['title'],
		name:"test",
	}
</script>
<template>
	<view>
		这是test组件
		这是父组件传递过来的数据{{title}}
		<button @click="sendnum">给父组件传值</button>
	</view>
</template>

兄弟组件之间传值

b组件使用uni.$on()注册全局事件

<template>
	<view>
		{{num}}
	</view>
</template>

<script>
	export default {
		name:"b",
		data() {
			return {
				num:0
			};
		},
		created() {
			// 注册全局事件
			uni.$on("updateNum",(num)=>{
				this.num+=num
			})
		}
	}
</script>

<style>

</style>

a组件使用uni.$emit()触发全局事件

<template>
	<view>
		这是a组件<button @click="addNum">修改B组件的数据</button>
	</view>
</template>

<script>
	export default {
		name:"a",
		data() {
			return {
				
			};
		},
		methods:{
			addNum(){
				uni.$emit('updateNum',10)
			}
		},

	}
</script>

<style>

</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值