1、在scr目录上新建store仓库
2、在index.ts文件里面配置
import { createPinia } from "pinia"
const pinia = createPinia()
// 在main.ts中使用
export default pinia
// 统一导出模板
export * from "./modules/app"
3、在modeules的app.ts文件里面定义navbarHeight
import { defineStore } from "pinia"
import { ref } from "vue"
// 定义一个store导出
export const useAppStore = defineStore("apostoreid",()=>{
const navbarHeight = ref(0);
// 定义一个方法修改navbarHeight
function changeNavBarHeight(data:number){
navbarHeight.value = data
}
return { navbarHeight,changeNavBarHeight }
})
4、在main.ts里面引入
import { createSSRApp } from "vue";
import App from "./App.vue";
import pinia from "./store"
export function createApp() {
const app = createSSRApp(App);
app.use(pinia)
return {
app,
};
}
5、使用淘宝镜像下载pinia
(1)、配置npm install -g cnpm --registry=https://registry.npm.taobao.org
(2)、npm install pinia@2.0.33
6、使用pinia 在app.vue中 onLaunch执行,传递系统信息至pinia
<script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { useAppStore } from "./store" //引入store
onLaunch(() => {
console.log("App Launch");
// 同步获取系统信息
let { safeAreaInsets } = uni.getSystemInfoSync();
console.log(safeAreaInsets);
let app = useAppStore(); //使用store
app.changeNavBarHeight(safeAreaInsets.top)
});
onShow(() => {
console.log("App Show");
});
onHide(() => {
console.log("App Hide");
});
</script>
<style></style>
7、在头部组件中使用
第一种方法利用store
<template>
<view :style="{paddingTop:app.navbarHeight+"px"}" class="headerbar">
<view style="height: 88rpx;">头部组件</view>
</view>
</template>
<script lang="ts" setup>
import { useAppStore } from "../../store"
let app = useAppStore()
console.log(app.navbarHeight);
</script>
<style>
.headerbar{
width: 100%;
background-color: red;
color: #fff;
}
</style>
第二种方法:利用组件传值
在首页引用头部组件往头部组件里面进行传值
<template>
<view class="content">
<headerbar :navbarHeight="app.navbarHeight"></headerbar>
<image class="logo" src="/static/logo.png" />
<view class="text-area">
<text class="title">{{ title }}</text>
</view>
</view>
</template>
<script setup lang="ts">
import headerbar from "../../components/headerbar/headerbar.vue"
import { useAppStore } from "../../store"
let app = useAppStore()
console.log(app.navbarHeight);
</script>
<style>
</style>
在头部组件里面用defineProps方法接受首页里面传递过来的值 注意加单位px
<template>
<view :style="{paddingTop:navbarHeight+'px'}" class="headerbar">
<view style="height: 88rpx;">头部组件</view>
</view>
</template>
<script lang="ts" setup>
import {defineProps} from "vue"
defineProps(["navbarHeight"])
</script>