4.vuex学习之getters、mapGetters

gettters可以理解为计算属性

在store.js中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//访问状态对象
const state = {
    count:1
}

const getters = {
    //vue2.0不要使用箭头函数,getters主要任务就是对状态state对象里面的数据,执行计算后输出
    count:function(state){
            return state.count+=100
    }
}
export default new Vuex.Store({
    state,
    getters
})

App.vue文件中

<template>
  <div id="app">
    
    <img src="./assets/logo.png">
    <h1>{{ msg}}</h1>
    <!--访问状态对象-->
    <div>{{$store.state.count}}</div>
    
    <!--getters中获取到的-->
<p>{{count}}</p> </div> </template> <script> //vuex提供的辅助函数 import {mapState,mapMutations,mapGetters,mapActions} from 'vuex' export default { name: 'app', data () { return { msg: 'Welcome to Your Vue.js App' } }, computed:{ count(){ return this.$store.getters.count }, // ...mapGetters([//使用mapGetters简写 // '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; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>

猜你喜欢

转载自www.cnblogs.com/tw6668/p/9107458.html