一、基本篇
安装
cnpm install pinia
src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './assets/main.css'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
src/stores/index.ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const thisVal=ref<object|string>({id:1});
const newVal=computed((val)=>{
return JSON.stringify(val)
})
const edit=(val:object)=>{
thisVal.value=val
}
return {thisVal,newVal,edit}
})
src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
component: () => import('../views/login.vue')
},
{
path: '/login',
name: 'login',
component: () => import('../views/login.vue')
},
{
path: '/main',
name: 'main',
component: () => import('../views/main.vue')
},
]
})
export default router
/src/views/login.vue
<template>
<div class="login">
{{thisVal}}
<input type="text" v-model="textVal">
<a href="#" @click.prevent="jump">跳</a>
</div>
</template>
<script setup lang="ts" >
import {ref, toRefs, watchEffect} from "vue"
import {useCounterStore} from "@/stores"
import router from "@/router";
const {thisVal}=toRefs(useCounterStore())
const textVal=ref<string>("2222")
const jump=()=>{
router.push({
path:"/main"
})
}
watchEffect(()=>{
thisVal.value=textVal.value
})
</script>
<style>
</style>
/src/views/main.vue
<template>
<div class="login">
{{thisVal}}
</div>
</template>
<script setup lang="ts" >
import {useCounterStore} from "@/stores"
const {thisVal}=useCounterStore()
</script>
<style>
</style>