先赞后看,养成好习惯!!!
这里我们挑一个案例来进行看看怎么去使用“应用生命周期函数”,这里我们选择“onLuanch函数”。
首先,我们会拿到一个最原始的index.vue初始代码
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
接着,我们要明白这个函数得放在index.vue的什么地方 ,如下:
<template>
<view class="content"></view>
</template>
<script>
export default {
onLaunch() {
console.log('App Launch'); // 这里可以添加一些初始化操作,比如读取本地存储的数据等。
// 读取本地存储的用户信息,并设置到全局变量中。
// 假设用户信息存储在名为 'userInfo' 的本地存储中。
try {
const userInfo = uni.getStorageSync('userInfo');
if (userInfo) {
this.globalData.userInfo x= userInfo;
}
} catch (e) {
console.error('获取本地存储失败: ', e);
}
},
globalData: {
userInfo: null
}
};
</script>
<style>
</style>
我们这里将onLuanch生命周期函数写在<script></script>标签里面,同样的道理,关于其他函数的代码,我们也是将函数写入<script></script>标签内,再去写入我们的业务逻辑。