uni-app 组件的创建及使用

uni-app中组件的创建

在uni-app中,可以通过创建一个后缀名为vue的文件,即创建一个组件成功,其他组件可以将该组件通过impot的方式导入,在通过components进行注册即可

  • 创建login组件,在component中创建login目录,然后新建login.vue文件

    <template>
    	<view>
    		这是一个自定义组件
    	</view>
    </template>
    
    <script>
    </script>
    
    <style>
    </style>
    
  • 在其他组件中导入该组件并注册

    import login from "@/components/test/test.vue"
    
  • 注册组件

    components: {test}
    
  • 使用组件

    <test></test>
    
组件的生命周期函数
beforeCreate在实例初始化之后被调用。详见
created在实例创建完成后被立即调用。详见
beforeMount在挂载开始之前被调用。详见
mounted挂载到实例上去之后调用。详见 注意:此处并不能确定子组件被全部挂载,如果需要子组件完全挂载之后在执行操作可以使用$nextTickVue官方文档
beforeUpdate数据更新时调用,发生在虚拟 DOM 打补丁之前。详见仅H5平台支持
updated由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。详见仅H5平台支持
beforeDestroy实例销毁之前调用。在这一步,实例仍然完全可用。详见
destroyedVue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。详见
组件的通讯
父组件给子组件传值

通过props来接受外界传递到组件内部的值

<template>
	<view>
		这是一个自定义组件 {{msg}}
	</view>
</template>

<script>
	export default {
		props: ['msg']
	}
</script>

<style>
</style>

其他组件在使用login组件的时候传递值

<template>
	<view>
		<test :msg="msg"></test>
	</view>
</template>

<script>
	import test from "@/components/test/test.vue"
	export default {
		data () {
			return {
				msg: 'hello'
			}
		},
		
		components: {test}
	}
</script>
子组件给父组件传值

通过$emit触发事件进行传递参数

<template>
	<view>
		这是一个自定义组件 {{msg}}
		<button type="primary" @click="sendMsg">给父组件传值</button>
	</view>
</template>

<script>
	export default {
		data () {
			return {
				status: '打篮球'
			}
		},
		props: {
			msg: {
				type: String,
				value: ''
			}
		},
		methods: {
			sendMsg () {
				this.$emit('myEvent',this.status)
			}
		}
	}
</script>

父组件定义自定义事件并接收参数

<template>
	<view>
		<test :msg="msg" @myEvent="getMsg"></test>
	</view>
</template>
<script>
	import test from "@/components/test/test.vue"
	export default {
		data () {
			return {
				msg: 'hello'
			}
		},
		methods: {
			getMsg (res) {
				console.log(res)
			}
		},
		
		components: {test}
	}
</script>
兄弟组件通讯
uni-ui的使用

uni-ui文档

1、进入Grid宫格组件

2、使用HBuilderX导入该组件

3、导入该组件

import uniGrid from "@/components/uni-grid/uni-grid.vue"
import uniGridItem from "@/components/uni-grid-item/uni-grid-item.vue"

4、注册组件

components: {uniGrid,uniGridItem}

5、使用组件

<uni-grid :column="3">
  <uni-grid-item>
    <text class="text">文本</text>
  </uni-grid-item>
  <uni-grid-item>
    <text class="text">文本</text>
  </uni-grid-item>
  <uni-grid-item>
    <text class="text">文本</text>
  </uni-grid-item>
</uni-grid>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值