如何共享状态
- 可以直接在一个JS文件内定义响应式变量,各组件分别引用,这样最简单,但是不支持SSR
- 使用provide/ inject插件的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
const userStore = () => {
const userInfo = ref("") const getUser = () => {
userInfo.value = userInfo_by_api; }
return {
getUser(), userInfo, .... } }
const user = Symbol() const useUser = () => inject(user)
export { user, userStore } export default useUser
import {user, userStore} from "path/to/user.js" const store = { install: (app: App) => { app.provide(user, userStore()); } }; export default store;
import store from "path/to/index.js" ...... createApp(App).use(store)
import useUser from "path/to/user.js" const user = useUser()
|
以下是vueconf中分享的方法,原理跟上面是一样的
