Vuex's most basic example of how to access state objects

In addition to the methods in "The Most Basic Example of Vuex" , there are two ways to access the state object state:

Just change the app.vue file

Method 1: Introduce computed

<template>
  <div id="app">
    <p>hello vuex</p>
    <p>{{$store.state.count}}</p>
    <p>{{count1}}</p>
    <button @click = "$store.commit('add')">+</button>
    <button @click = "$store.commit('reduce')">-</button>
  </div>
</template>

<script>
export default {
  name: 'App',
   data(){
     return {
       count: 1
     }
   },
   computed:{
     count1(){
      return this.$store.state.count+1
     }
   }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Method 2: Introduce mapState on the basis of method 1

<template>
  <div id="app">
    <p>hello vuex</p>
    <p>{{$store.state.count}}</p>
    <p>{{count1}}</p>
    <button @click = "$store.commit('add')">+</button>
    <button @click = "$store.commit('reduce')">-</button>
  </div>
</template>

<script> 
import { mapState } from 'vuex'   // Note here 
export default {
  name: 'App',
   data(){
     return {
       count: 1
     }
   },
   computed: mapState({
     count1: state => state.count //here
   })
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Method 3: Simplified mapState writing

<template>
  <div id="app">
    <p>hello vuex</p>
    <p>{{$store.state.count}}</p>
    <p>{{count}}</p> //Here is the count
    <button @click = "$store.commit('add')">+</button>
    <button @click = "$store.commit('reduce')">-</button>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'App' ,
   // data(){ //The count in data should be commented out here, otherwise it will not take effect, and I don't know the reason. This is not the same as the video tutorial 
  //    return { 
  //      count: 1 
  //    } 
  // }, 
  computed: mapState([
     'count'
  ])
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

The results are as follows:

See, the result is the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212173&siteId=291194637