Uniapp中使用vue3语法
在setup语法糖中调用uniapp的页面生命周期
<script setup>import { onShow } from "@dcloudio/uni-app"onShow(() => {//hanlder...})
</script>
vue2混入在vue3中建议使用组合式API
新建baseHook.js
import { ref } from "vue";
export function useBaseHook() {//响应式引入界面之后值变化 页面数据也会发生改变const userList = ref([])async function getUserList() {let requestRes = await request({//....})userList.value = requestRes.rows}return {userList,getUserList}
}
页面上使用
<script setup>import {useBaseHook} from '../utils/baseHook.js'let {userList,getUserList} = useBaseHook()
</script>
状态管理Pinia
uniapp教程官网Pinia用法
HBuilder X 已内置了 Pinia,无需手动安装,按照下方示例使用即可。
main.js添加
import App from './App'
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';export function createApp() {const app = createSSRApp(App);app.use(Pinia.createPinia());return {app,Pinia, // 此处必须将 Pinia 返回};
}
创建一个 Store
// stores/counter.js
import { defineStore } from 'pinia';export const useCounterStore = defineStore('counter', {const count = ref(0);function increment() {count.value++;}return { count, increment };
});
页面使用
<script setup>import { useCounterStore } from '@/stores/counter'const counter = useCounterStore()counter.count++counter.$patch({ count: counter.count + 1 })// 或使用 action 代替counter.increment()
</script>
<template><!-- 直接从 store 中访问 state --><div>Current Count: {{ counter.count }}</div>
</template>
页面跳转、传值在setup语法糖中(vue3)
跳转页
uni.navigateTo({url: "/pages/.../...",success: (e) => {e.eventChannel.emit('infoKey', 任意参数)}
})
接收页面
import { onShow,onLoad } from "@dcloudio/uni-app"
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance().proxy
onLoad(() => {//或者onShow(() => {//在vue2语法中直接this.getOpenerEventChannel(),就能拿到eventChannel //但是在vue3中好像没this的概念 用 getCurrentInstance().proxy代替了const eventChannel = instance.getOpenerEventChannel();eventChannel.on('infoKey', function(data) {console.log('infoKey', data)})
})