Thursday 1 April 2021

How to add MapState to the Computed items - calling Vuex in Vue.js

 So after using several Form validations I’m using in the form from Vuex Store, my code looks like this


computed:{
swellitems(){
return this.$store.state.swellitems
},
weather_sky(){
return this.$store.state.weather_sky
},
weather_wet_dry()
return this.$store.state.weather_wet_dry
},
survey_type(){
return this.$store.state.survey_type
},
one_to_three(){
return this.$store.state.one_to_three
},
wind_force(){
return this.$store.state.wind_force
},
wind_direction(){
return this.$store.state.wind_direction
},
sea_state(){
return this.$store.state.sea_state
},
tide_state(){
return this.$store.state.tide_state
},
tide_movement(){
return this.$store.state.tide_movement
},


Way before this point I’m thinking there must be a better way to deal with this ( although laziness means I don’t hunt it down until it gets this bad. ).
The method we want to use is ‘mapState’

computed:{
...mapState(['swellitems', 'weather_sky', 'weather_wet_dry','survey_type',
'one_to_three', 'wind_force', 'wind_direction','sea_state', 'tide_state', 'tide_movement'])
}

The ‘…' won’t work straight out of the box though. We’ll need to install ‘bable’

INSTALLING BABEL FOR VUEX

Babel-Plugin-Vuex-Store (shortly vx for Vuex) packs along a couple of features to simplify your Vuex-related coding. Installation and usage.

npm install babel-plugin-vuex-store

and then

npm install babel-preset-stage-2 --save-dev

You'll also need to import mapState into your Script

import { mapState } from 'vuex';

After this, my code works and looks my organised :) .


No comments: