046、Vue3+TypeScript基础,pinia库中使用$subscribe订阅数据变动
01、main.js代码如下:
// 引入createApp用于创建Vue实例 import {createApp} from 'vue' // 引入App.vue根组件 import App from './App.vue' //第一步:引入pinia import {createPinia} from 'pinia' const app = createApp(App); //第二步:创建pinia实例 const pinia = createPinia() //第三步:将pinia实例挂载到Vue实例上 app.use(pinia) // App.vue的根元素id为app app.mount('#app')
02、App.vue代码如下:
<template> <div class="app"> <h2 class="title">App.Vue</h2> <!-- <Page1/>--> <br> <Page2/> </div> </template> <script lang="ts" setup name="App"> // import Page1 from "@/view/Page1.vue"; import Page2 from "@/view/Page2.vue"; </script> <style scoped> .app { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; } .nav-button { display: inline-block; /* 让链接显示为块级元素,以便应用宽度和高度 */ padding: 10px 20px; /* 内边距 */ margin: 0 5px; /* 外边距,用于按钮之间的间隔 */ text-decoration: none; /* 移除下划线 */ color: white; /* 文本颜色 */ background-color: #007bff; /* 背景颜色 */ border-radius: 5px; /* 边框圆角 */ transition: background-color 0.3s; /* 平滑过渡效果 */ } .nav-button:hover { background-color: #0056b3; /* 鼠标悬停时的背景颜色 */ } .nav-button.router-link-active { background-color: #28a745; /* 当前激活(路由匹配)时的背景颜色 */ } .mai-content { /* 添加边框样式 */ border: 2px solid #000; /* 边框宽度、样式和颜色 */ border-radius: 5px; /* 可选:添加边框圆角 */ padding: 20px; /* 可选:给内部内容添加一些内边距 */ margin: 20px; /* 可选:给元素添加一些外边距,以便与其他元素隔开 */ } </style>
03、Page2.vue代码如下:
<template> <div class="mypage"> <button @click="getLoveTalk">获取一句土味情话</button> <ul> <li v-for="talk in talklist" :key="talk.id">{{ talk.id }} -- {{ talk.title }} </li> <br> </ul> </div> </template> <script lang="ts" name="page2" setup> import {usesTalkStore} from "@/store/myTalk"; import {storeToRefs} from "pinia"; const myTalkStore = usesTalkStore(); //从myTalkStore去除talklist const {talklist} = storeToRefs(myTalkStore); myTalkStore.$subscribe((mutation, state) => { console.log('myTalkStore数据变化', mutation, state.talklist) localStorage.setItem("talklist", JSON.stringify(state.talklist)) }) function getLoveTalk() { myTalkStore.getLoveTalk() } </script> <style scoped> .mypage { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
04、myTalk.ts代码如下:
import {defineStore} from 'pinia' import axios from 'axios' import {nanoid} from 'nanoid' export const usesTalkStore = defineStore('talk', { actions: { async getLoveTalk() { // 调用接口,获取情话 let result = await axios.get( 'https://api.uomg.com/api/rand.qinghua?format=json') let obj = {id: nanoid(), title: result.data.content} this.talklist.unshift(obj) }, }, //真正存储数据的地方 state() { return { // 加上|| [],规避为空的情况 talklist: JSON.parse( localStorage.getItem('talkList') as string ) || [] } } })
05、效果如下:
06、效果如下: