<!-- any *.vue file --><template><!-- lot of code -->
{{ first_name }}
<br/><br/><labelfor="firstName">First Name</label><inputname="firstName"type="text"v-model="first_name"/><!-- code --></template><script>import{mapState,mapMutations}from"vuex";// more code
exportdefault{computed:{...mapState("contact",["first_name"]),},methods:{...mapMutations("contact",["setFirstName"]),validateAndUpdateFirstName(val){if(val.length>2)this.setFirstName(val);elsethrownewException("Are you sure you are a real person?");},},};</script>
This is cool, but you can save a bunch of “typing” - which brings us to Option 2.
Option 2: Use Pathify
Instead of doing a mapState and mapMutations - you let Pathify handle everything for you.
<template><!-- code --></template><script>import{sync}from"vuex-pathify";exportdefault{computed:{...mapSync("contact","first_name"),// you can access first_name or update it directly
},methods:{validateAndUpdateFirstName(val){if(val.length>2)this.first_name=val;elsethrownewException("Are you sure you are a real person?");},},};</script>
Option 3: Use store as a function
You could just use store to access access or update state. This more common in store modules.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/store/contact.js
importstorefrom"../store";// ... code
exportdefault{actions:{asyncupdateContact({commit},params){// ..
store.set("action/updateCall",actionData);// `commit("action/updateCall",actionData, { root: true }) does the same thing - but only sane people do that
},},};// ...code
Accessing store from a router is similar to the above depiction.
You could import the store in your components/views as well and do the same, but there is a shortcut -
<template><!-- code -->
{{ firstName }}
<!-- code --></template><script>exportdefault{computed:{firstName(){returnthis.$store.state.contact.first_name;},// you can access first_name or update it directly
},methods:{validateAndUpdateFirstName(val){if(val.length>2)this.$store.commit("setFirstName",val);elsethrownewException("Are you sure you are a real person?");},},};</script>
Recommendation
Use Pathify. Period.
If you don’t want to use a third party library - use Vuex helper functions like mapState. You will make it easier on yourself by standardizing the state access/updates throughout the project, and more importantly, cutting across development teams.