引入:
<script setup>
import { createAppKit,useAppKitEvents } from '@reown/appkit/vue'
import { arbitrum, mainnet, polygon, base } from '@reown/appkit/networks'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { watch } from 'vue'
// 1. Get projectId from https://dashboard.reown.com
// 注意设置domain
const projectId = 'xxxxxx'
// 2. Create a metadata object
const metadata = {
name: 'AppKit',
description: 'AppKit Example',
url: window.location.origin, // 自动跟当前域名保持一致
icons: ['https://avatars.githubusercontent.com/u/179229932']
}
// 3. Set the networks
const networks = [mainnet, polygon, base]
// 4. Create Wagmi Adapter
const wagmiAdapter = new WagmiAdapter({
networks,
projectId
})
// 5. Create the modal
const modal = createAppKit({
adapters: [wagmiAdapter], // 只保留钱包适配器
networks,
projectId,
metadata,
features: {
analytics: true,
socials: [], // 清空社交登录
email: false
},
themeMode: "light",
uiPreferences: {
view: "compact"
},
});
</script>
公共头部显示钱包登录按钮
import {
ref,
onMounted,
watch
} from "vue";
import { useAppKit,useAppKitAccount,useDisconnect,useWalletInfo,useAppKitEvents } from '@reown/appkit/vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
// 调用 hook
const { open, close, account, network, status } = useAppKit()
const accountData = useAppKitAccount();
const { disconnect } = useDisconnect()
//登录按钮
const connectFunc = async()=>{
// await disconnect()
await open() // 打开连接弹窗,等待用户操作
}
//钱包内的disconnect
useAppKitEvents({
disconnect: () => {
console.log('钱包已断开')
userStore.clearProfile()
},
connect: (account) => {
addressText.value = account.address.slice(0, 4) + '...' + account.address.slice(-6)
}
})
//监听钱包地址
watch(
() => accountData.value?.address,
(adr,old) => {
if (adr){
addressText.value = truncateAddress(accountData.value.address)
if (!userStore.token){
//获取到钱包地址以后,未登录状态下去登录
loginFunc(accountData.value.address)
}
}else{
//获取不到钱包地址后退出
userStore.clearProfile()
uni.reLaunch({
url: '/pages/index/index'
});
//这两个clear非常重要,否则会导致明明退出成功了,但是accountData依然是connect状态
uni.clearStorageSync(); // 清理 localStorage
uni.clearStorage(); // 异步清理
}
}
)
//手动disconnect按钮
const disConnectFunc = async()=>{
await disconnect()
userStore.clearProfile()
addressText.value = ''
uni.reLaunch({
url: '/pages/index/index'
});
//这两个clear非常重要,否则会导致明明退出成功了,但是accountData依然是connect状态
uni.clearStorageSync(); // 清理 localStorage
uni.clearStorage(); // 异步清理
// 短暂延迟后刷新页面
setTimeout(() => {
window.location.reload();
}, 100);
}
1.本地测试也需要设置下domain
2.本地测试可手动清理localStorage去测试
3.如本地一直退出不成功,可部署到线上调试,线上不行的话就是代码有问题。