How to import vuex store in typescript?

by dalton_moen , in category: Javascript , 6 months ago

How to import vuex store in typescript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@dalton_moen 

In TypeScript, you can import a Vuex store by creating a file that exports a Vuex store instance and then importing that file into your components.


First, create a file to define and export your Vuex store. This file could be named store.ts or index.ts, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  // Define your state, mutations, actions, and modules here
});

export default store;


Then, in your main Vue component file (such as App.vue), import the Vuex store:

1
2
3
4
5
6
7
8
9
import Vue from 'vue';
import Component from 'vue-class-component';
import store from './store';

@Component
export default class App extends Vue {
  // Use the store as a class property
  private store = store;
}


Now, you can access the Vuex store in your Vue components through the this.$store property:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import Vue from 'vue';
import Component from 'vue-class-component';
import { mapState } from 'vuex';

@Component({
  computed: {
    // Use mapState to map Vuex state to component properties
    ...mapState(['counter'])
  }
})
export default class MyComponent extends Vue {
  // Access the store state with this.counter
  private counter!: number;
}


By following these steps, you can import and use a Vuex store in your Vue.js TypeScript application.