vue3备忘pinia
准备
- 在main中创建实例并挂载
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(router)
app.use(pinia)
app.mount('#app')
- 配置
定义后必须return
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
const userTestStore = defineStore('userTestStore', () => {
const a = ref(1)
const b = ref(2)
const sum = computed(() => {
return a.value + b.value
})
function addA() {
a.value++
}
return { a, b, sum, addA }
})
export default userTestStore
使用
<template>
<div>
<router-link to="/comB/47">toB</router-link>
{{ store.a }} + {{ store.b }} = {{ store.sum }}
<button @click="store.addA()">+1</button>
</div>
</template>
<script setup>
import userTestStore from "../store/index.js"
const store = userTestStore()
</script>
<style scoped lang="less">
</style>