1

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.
image.png

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>

11.gif

The data of "pinia" can also be observed in the vue-devtools console.

image.png

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🐟


铁皮饭盒
5k 声望1.2k 粉丝

喜欢写程序: [链接]