Vuex訪問狀態對象的方法 Vuex最基本樣例》

除了《Vuex最基本樣例》中的方法外,還有兩種方法訪問狀態對象state:html

只須要改app.vue文件vue

方法一:引入computedweb

<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>

方法二:在方法一基礎上引入mapStatevuex

<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'  //注意這裏
export default {
  name: 'App',
   data(){
     return {
       count: 1
     }
   },
   computed: mapState({
     count1: state=>state.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>

方法三:簡化的mapState寫法app

<template>
  <div id="app">
    <p>hello vuex</p>
    <p>{{$store.state.count}}</p>
    <p>{{count}}</p>  //這裏是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(){  //這裏要註釋掉data裏的count,不然不生效,不知道緣由。這點和視頻教程不太同樣
  //   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>

運行結果以下:post

看出來,結果是同樣的。this

相關文章
相關標籤/搜索