How to display the value from store in vuex?

Member

by ryleigh , in category: Javascript , 8 months ago

How to display the value from store in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 8 months ago

@ryleigh 

To display the value from the store in Vuex, you would typically use computed properties in your Vue component. Here's an example of how to do this:

  1. First, define a getter in your Vuex store to retrieve the value you want to display. For example, if you have a state called myValue in your store, you can create a getter like this:
1
2
3
4
5
6
7
8
9
// store.js
const store = new Vuex.Store({
  state: {
    myValue: 'Hello World'
  },
  getters: {
    myValue: state => state.myValue
  }
});


  1. In your Vue component, you can access the getter using mapGetters from Vuex and display the value in your template like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<template>
  <div>{{ myValue }}</div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['myValue'])
  }
};
</script>


In this example, the value of myValue from the store will be displayed in the template of your Vue component. Make sure you have imported the necessary Vuex packages and have set up your store before using getters in your components.