If it is a new project, it is completely based on setup, then it is recommended to use pinia instead of vuex. The vuex official website says that pinia can be understood as vuex5, and vuex will not be released.
Install
npm i pinia -S
use
First introduce "pinia" in "main.js" and associate it with the "vue" instance.
import { createApp } from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
const pinia = createPinia();
createApp(App).use(pinia).mount('#app')
Then create "store", the first parameter of defineStore
is the id of the store, which can be any character, the definition data can be used ref
computed
reactive
computed
, note that the export is a function.
import { defineStore } from 'pinia'
import { ref,computed } from 'vue';
export const useStore = defineStore('main', () => {
const title = ref(`hello pinia`)
const list = reactive([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const count = computed(() => list.reduce((a, b) => a + b));
function add(){
list.push(1)
}
return { title, count,list,add }
})
Inside the component:
<template>
<p>标题: {{ store.title }}</p>
<p>总数: {{ store.count }}</p>
<p>列表: {{ store.list }}</p>
<button @click="store.add">加1</button>
</template>
<script setup>
import { useStore } from "@/pStore";
const store = useStore();
</script>
The data of "pinia" can also be observed in the vue-devtools console.
Summarize
There are actually two ways to use pinia, one is the abbreviation of this article, and the other is the definition of "state/getters/action" similar to vuex. From the perspective of code simplicity, I prefer the way of writing this article. If you like the way of writing vuex, You can refer to pinia official documentation to learn.
https://pinia.vuejs.org
online demo
https://vue3-start-phi.vercel.app/#/pinia
🍕Learn to interact
Thank you for reading, if you have any questions, you can add me on WeChat, I will pull you into the group to fish🐟
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。