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 | 挂载到实例上去之后调用。详见 注意:此处并不能确定子组件被全部挂载,如果需要子组件完全挂载之后在执行操作可以使用$nextTick Vue官方文档 | ||
beforeUpdate | 数据更新时调用,发生在虚拟 DOM 打补丁之前。详见 | 仅H5平台支持 | |
updated | 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。详见 | 仅H5平台支持 | |
beforeDestroy | 实例销毁之前调用。在这一步,实例仍然完全可用。详见 | ||
destroyed | Vue 实例销毁后调用。调用后,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的使用
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>