pinia是一个比较新的状态管理库
下面来讲解一下pinia的食用方法。
vue3挂载pinia
src/mian.js
import pluginInstall from "./plugins";
import { createApp } from "vue";
import AppElement from "./App.vue";
let app;
async function render(props = {}) {
  const { container } = props;
  app = createApp(AppElement);
  app.use(pluginInstall);
  app.mount(container ? container.querySelector("#app") ?? "#app" : "#app");
  return app;
}
render();
src/plugins/index.js
import piniaInstall from "./pinia";
export default function install(app) {
  app.use(piniaInstall);
}
src/plugins/pinia/index.js
import { createPinia } from 'pinia';
export default createPinia();
接下来创建stores
src/stores
src/stores/test.js
import { defineStore } from 'pinia';
export const useStoreTest = defineStore('test', {
	state: () => ({
		_text: '测试1',
		_num: 2
	}),
	getters: {
		text: ({ _text }) => 'getters:' + _text,
		doubleNum: ({ _num }) => _num * 2,
		andText2: ({ _text }) => {
			const Test2 = useStoreTest2()
			const { text2,_text2 } = Test2
			return `${_text} -- ${text2} --- ${_text2}`
		},
	},
	actions: {
		setText(text) {
			this.text = text
		},
	},
});
export const useStoreTest2 = defineStore('test2', {
	state: () => ({
		_text2: '测试2',
	}),
	getters: {
		text2: ({ _text2 }) => 'getters:' + _text2,
	},
	actions: {
		setText2(text) {
			this._text2 = text
			console.log("setText2",this._text2)
		},
	},
});
defineStore( store的唯一id,option )
option: {
    state:{},
    getters:{},
    actions:{}
    ...
}
实际运用
<template>
	<div class="homepage">
		<p>{{ text }}</p>
		<p>{{ _num }}</p>
		<p>{{ doubleNum }}</p>
		<p>{{ text2 }}</p>
		<p>{{ andText2 }}</p>
		<button @click="setText2('黑黑黑')">change test2</button>
	</div>
</template>
<script setup>
import { useStoreTest, useStoreTest2 } from "@/stores/test"
import { storeToRefs } from "pinia";
const test1 = useStoreTest()
const test2 = useStoreTest2()
---如果不改为ref 数据就只是一次性的赋值
---const { text, doubleNum, andText2 } = test1 
---使用pinia的storeToRefs将test1中的内容转换为ref,支持解构赋值
const { text, _num, doubleNum, andText2 } = storeToRefs(test1) 
---photo:1. 这里的text2由于不是storeToRefs结构出来的值,所以不会获得响应更新视图
const { text2, setText2 } = test2; 
console.log(text.value, doubleNum.value, andText2.value, text2)
</script>
<style>
button {
	background-color: rgba(0, 0, 0, 0.2);
}
</style>
 


2022.3.19---ps
解释一下为什么state对象里的属性名要用 _ 作为前缀,其实这东西是flutter里的私有化变量的语法,
这么做是为了保证数据不被随意修改,要用到的就用getters返回出去,其他的就在内部里使用。
修改就用actions定义函数就好了。其实pinia虽然简单,但是状态的隐私还是得保护一下的。
不然跟短裤外穿没啥区别,除非你是超人可以随意。
					
		
		最后于  2022-3-19		
				被海星吧编辑
				
		,原因: