一、如何使用自定义组件
1、挂载在main.js中
使用 import 语法引入组件路径,使用 Vue.component() 方法全局注册组件后,可以在各个页面中无需引入,直接使用(使用时记得首字母是大写)。
2、使用在单页面中
import 引入后,在 component 里注册,最后在 template 中使用。
3、为什么我的组件钩子失效?console打印不出东西?
在 uniapp 自定义组件中,不可以使用 onLoad()、onShow()、onReady()等等 uniapp 的生命周期,在自定义组件中需要换成 vue 的生命周期。
二、分享我写的实时获取当前时间的组件
当前此组件的字体颜色、字体大小、字体宽度,是通过父组件传递进来的。
如果你想实现更完整,具有api更多的功能,可以在组件上增加些自己想要的逻辑,再通过父子传递来实现效果。
<template>
<view class="timeCounter">
<text :style='{ color: fontColor, fontSize: fontSize, fontWeight: fontWeight }'>
{{ time }}
</text>
</view>
</template>
<script>
export default {
name: "timeCounter",
components: {},
data() {
return {
time: null,
intervalTimer: null,
};
},
props: {
fontColor: {
type: String,
default: '#666666'
},
fontSize: {
type: String,
default: '32rpx'
},
fontWeight: {
type: Number,
default: 700
}
},
computed: {},
watch: {},
mounted() {
this.getTime();
this.intervalTimer = setInterval(this.getTime, 1000);
},
destroyed() {
clearInterval(this.intervalTimer);
},
methods: {
getTime() {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
hours = hours < 10 ? `0${hours}` : hours;
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
this.time = `${hours}:${minutes}:${seconds}`;
console.log(this.time);
},
},
};
</script>
<style lang='scss' scoped>
.timeCounter {
display: flex;
align-items: center;
justify-content: center;
> text {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
</style>