pinia官网:https://pinia.vuejs.org/
pinia菠萝挺不错,简单又灵活。
1.安装:yarn add pinia 或者 npm install pinia,全局加 --location=global
2.注册使用 main.js
pinia菠萝挺不错,简单又灵活。
1.安装:yarn add pinia 或者 npm install pinia,全局加 --location=global
2.注册使用 main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
//异常统一处理
app.config.errorHandler = (err) => {
/* handle error */
console.log("exception:" + err);
}
3.在src目录下创建store文件夹,然后创建counter.js文件,名字自己定,官网参考:https://pinia.vuejs.org/core-concepts/
方式一 options stores
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
//方式一
// state: () => {
// return { count: 0,user_name:'jay.star' }
// },
//方式二
state: () => ({ count: 0, user_name: 'jay.star' }),
//相当于计算属性 computed
getters: {
doubleCount: (state) => state.count * 2,
},
//相当于 methods
actions: {
increment() {
this.count++
},
},
});
方式二setup stores
import { defineStore } from 'pinia'
import { ref,computed } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const user_name = ref("jay.star");
//getters
const doubleCount = computed(() => count.value * 2);
//即 actions 和 methods
function increment() {
count.value++
}
return { count, user_name, doubleCount, increment };
});
4.使用 getters 可以直接 {{counter.doubleCount}}
<script setup>
import { useCounterStore } from "@/stores/counter";
const counter = useCounterStore();
// 直接修改
counter.count++;
// $patch
counter.$patch({ count: counter.count + 1 });
// action
counter.increment();
</script>
可以定义多个,一般是再建一个文件,比如 userinfo.js,然后里面再写一个 export const useUserInfoStore = defineStore('userinfo',{...});
更多参考官网
浙公网安备 33010602011771号