Skip to content

Instantly share code, notes, and snippets.

@asvae
Last active October 11, 2019 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asvae/196ee7c3afb20e39d5a67f2de3c7e899 to your computer and use it in GitHub Desktop.
Save asvae/196ee7c3afb20e39d5a67f2de3c7e899 to your computer and use it in GitHub Desktop.
Inject-provide store example

Plugin (store-plugin.ts)

import { CheckOutStore } from '../services/store'

export const checkOutStoreInjectKey = Symbol('checkOutStore')

export const StorePlugin = {
  install (Vue: any): void {
    Vue.mixin({
      inject: {
        $coStore: {
          from: checkOutStoreInjectKey,
          default: undefined,
        },
      },
    })
  },
}

declare module 'vue/types/vue' {

  interface Vue {
    $coStore: CheckOutStore
  }
}

Demo file (Store.demo.vue)

<template>
  <VbDemo>
    <VbCard>
      <pre>{{$coStore}}</pre>
    </VbCard>
    <VbCard title="value">
      <input type="text" v-model="$coStore.testValue">
      <pre>{{$coStore.testValue}}</pre>
    </VbCard>
    <VbCard title="valueNested">
      <input type="text" v-model="$coStore.testValueNested.nested">
      <pre>{{$coStore.testValueNested}}</pre>
    </VbCard>
  </VbDemo>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component({
  components: {  },
})
export default class StoreDemo extends Vue {
}
</script>

Helpers (vue-helpers.ts)

import Vue from 'vue'

export function observe<T> (value: T): T {
  new Vue({ data: { value } })
  return value
}

Root component (App.vue)

<template>
  <div id="q-app">
    <router-view />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { StorePlugin, checkOutStoreInjectKey } from './boot/store-plugin'
import { observe } from './helpers/vue-helpers'
import { CheckOutStore } from './services/store'

Vue.use(StorePlugin)

@Component({
  provide() {
    return {
      [checkOutStoreInjectKey]: observe(new CheckOutStore()),
    }
  },
})
export default class App extends Vue {

}
</script>

Store (store.ts)

// Store is acccessible as $coStore in components.

export type EditorPosition = 'right' | 'left' | 'full' | 'bottom'

class DrawerState {
  editorShownState = true
  selectedCard: any = {}
  editorPosition: EditorPosition = 'right'
}

export class CheckOutStore {
  drawerState = new DrawerState()

  testValue = 'test'
  testValueNested = {
    nested: 'test nested'
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment