Vue 3.x & Pinia Actions All In One
Vue 3.x & Pinia Actions All In One
store 本质上就是一个全局的对象, Pinia Actions 类似 Vue 里面的 methods
single store
import { defineStore } from 'pinia';
// export declare function defineStore<Id extends string, S extends StateTree = {}, G extends _GettersTree<S> = {}, A = {}>(id: Id, options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>): StoreDefinition<Id, S, G, A>;
export const appStore = defineStore('appStore', {
state() {
return {
msg: "Hello World!",
};
},
getters: {
// computed
getMsg(): string {
return `👻 ${this.msg}`;
}
},
actions: {
// methods
updateMsg(str: string) {
this.msg = str;
},
async fetchData(url: string) {
const json = await fetch(url).then(res => res.json());
// console.log('json =', json);
return json;
},
},
});
<template>
<!-- <>react fragment</> -->
<!-- <template>vue fragment</template> -->
<template v-if="true">
<div>{{store.msg}}</div>
</template>
<template v-if="true">
<div>{{store.getMsg}}</div>
<!-- <pre>{{jsonString}}</pre> -->
<pre>❓ {{store.msg}}</pre>
<span v-pre>{{ this will not be compiled }}❓ {{store.msg}}</span>
<button @click="updateMsg">Pinia 🍍</button>
</template>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { appStore } from "../store/index";
// import { appStore } from "@/store/index";
// 实例化 store
const store = appStore();
const log = console.log;
log(`store =`, store);
let jsonString = ref('');
const url = `https://cdn.xgqfrms.xyz/json/cat.json`;
// async await
store.fetchData(url).then(json => {
// console.log('fetchData =', json);
jsonString.value = JSON.stringify(json, null, 4);
// console.log('jsonString =', jsonString);
console.log('jsonString.value =', jsonString.value);
});
// const promise = store.fetchData(url);
// promise.then(json => {
// console.log('fetchData =', json);
// });
const updateMsg = () => {
store.$patch({
msg: "Hello Pinia 🍍!",
});
// store.updateMsg('Pinia 🍍');
}
</script>
<style scoped lang="scss">
.className {
color: #000;
background: #fff;
}
</style>
store.$patch
multi store
import { useAuthStore } from './auth-store'
// useSettingsStore
export const useSettingsStore = defineStore('settings', {
state: () => ({
preferences: null,
// ...
}),
actions: {
async fetchUserPreferences() {
// useSettingsStore
const auth = useAuthStore();
if (auth.isAuthenticated) {
this.preferences = await fetchPreferences()
} else {
throw new Error('User must be authenticated')
}
},
},
});
https://pinia.vuejs.org/core-concepts/actions.html#accessing-other-stores-actions
storeToRefs
store state 解构,数据不响应式 bug, 需要使用 storeToRefs 包裹 ✅
store action 可以直接解构,不需要使用 storeToRefs 包裹
import { storeToRefs } from 'pinia'
export default defineComponent({
setup() {
const store = useStore()
// `name` and `doubleCount` are reactive refs
// This will also create refs for properties added by plugins
// but skip any action or non reactive (non ref/reactive) property
const { name, doubleCount } = storeToRefs(store)
// the increment action can be just extracted
const { increment } = store
return {
name,
doubleCount
increment,
}
},
})
https://pinia.vuejs.org/core-concepts/#using-the-store
https://pinia.vuejs.org/api/modules/pinia.html#storetorefs
mapActions
not to use Composition API
import { mapActions } from 'pinia'
import { useCounterStore } from '../stores/counterStore'
export default {
methods: {
// gives access to this.increment() inside the component
// same as calling from store.increment()
...mapActions(useCounterStore, ['increment'])
// same as above but registers it as this.myOwnName()
...mapActions(useCounterStore, { myOwnName: 'doubleCounter' }),
},
}
store.$onAction()
export default {
setup() {
const someStore = useSomeStore()
// this subscription will be kept after the component is unmounted
someStore.$onAction(callback, true)
// ...
},
}
regexp group
信息加密,电话号码隐藏
const phoneNumber = `18123456789`;
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$2');
// '181****2345' ❌
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
// '181****6789' ✅
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1$2****');
// '1812345****' ❌
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
const phoneNumber = `18123456789`;
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, function(match, group1, group2, group3) {
console.log("match, group1, group2, group3 =", match, group1, group2, group3);
});
// match, group1, group2, group3 = 18123456789 181 2345 6789
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, (match, group1, group2, group3) => {
console.log("match, group1, group2, group3 =", match, group1, group2, group3);
});
// match, group1, group2, group3 = 18123456789 181 2345 6789
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, (match, ...groups) => {
console.log("match, groups =", match, groups);
});
// match, groups = 18123456789 (5) ['181', '2345', '6789', 0, '18123456789']
RegExp group
https://regexper.com/#%2F^(\d{3})(\d{4})(\d{4})%24%2F
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16168901.html
未经授权禁止转载,违者必究!