npm.io
1.0.0 • Published 4 years ago

sharem

Licence
ISC
Version
1.0.0
Deps
1
Size
5 kB
Vulns
0
Weekly
0
DeprecatedThis package is deprecated

sharem

share modular

  • 优点: 简单明了好上手

sharem是基于Vue3.0开发的状态管理工具(参考Vuex、Pinia),相比于Vuex,我们更倾向于Pinia的轻量级,因此sharem"借鉴"了Pinia的Api

目录

安装

将sharem添加为项目的依赖

$ npm install sharem

在你的项目中引用它:

// 导入 sharem模块 的Api
import { defineStore, storeToRefs } from 'sharem'

API

defineStore(options)

defineStore将会返回一个函数,执行这个函数可以拿到options转换后拿到store对象

属性 类型 描述
eventName Objecet 配置选项 详见

代码示例

const useCountStore = defineStore({
	state: () => ({
		num: 0 
	}),
	actions: {
		increase() {
			this.num++
		}
	},
})
useCountStore() // => store对象
options

options是一个对象,以下是它的数据格式

属性 类型 描述
state Function state数据,参考vue2的 data函数
actions Objecet 方法体(可选),参考vue2组件中的 methods
代码示例
{
	state: () => ({
		num: 0 
	}),
	actions: {
		increase() {
			// 此时的this可以访问到 state 以及 actions里的内容
			this.num++
			this.test()
		},
		test(){
			console.log(1)
		},
	}
}
storeToRefs(store)

返回被解构store对象,只是想操作store里的某个数据或者看起来更简单,可以使用它

属性 类型 描述
store String 事件名
callback Function 回调函数

代码示例

import { storeToRefs } from 'sharem'
import useCountStore from '@/stroe/useCountStore'
// template模板中使用=> {{ countStore.num }}  太麻烦   
const countStore = useCountStore()
countStore.num++


// 使用如下 template模板中使用=> {{ num }}
const { num } = storeToRefs(useCountStore)
num.value++

示例

// useCountStore.js 中定义状态管理数据 并导出
export default defineStore({
	state: () => ({
		count: 0 
	}),
	actions: {
		increment() {
			this.count++;
		}
	}
})
// index.vue 中导入,并使用
import useCountStore from 'useCountStore.js'
setup(){

	const countStore = useCountStore()
	// 可以直接修改
	countStore.num++
	
	// $patch与$reset为 每个store对象自带的Api,无需重复编写
	
	// 或者使用$patch
	countStore.$patch({
		num: countStore.num++
	})
	// 更推荐这中写法
	countStore.$patch(store=>{
		store.num++
	})
	// 调用该方法会将 options.state里的值初始化,慎用!
	countStore.$reset()
	
	return { countStore }
}
<!-- 在index.vue的template中使用 -->
<template>
	<div>
		{{ countStore.num }}
	</div>
</template>

Keywords