Vuex getters - example of using mapGetters or mapState

0 votes
1,247 views
added Jul 30, 2018 in Vue by LC Marshal Captain (25,790 points)
//store.js

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({ 
    plugins: [createPersistedState()],
    state: {
        pid: null,
        uid: null,
        act: null,
        propertyData: null,
        listOfUnits: null,
        unit: null,
        // payable: 1000,
        // paytest: 2/100,
        fundingAmount: 20000,
    },
    mutations: {
        setUid(state, payload) {
            state.uid = Number(payload)
        },
        setAct(state, payload) {
            state.act = payload
        },
        setPid(state, payload) {
            // clear data
            if (state.pid && state.pid !== Number(payload)) {
                state.propertyData = null
                state.listOfUnits = null
                state.unit = null
            }

            state.pid = Number(payload)
        },
        setPropertyData(state, payload) {
            state.propertyData = payload
        },
        setListOfUnits(state, payload) {
            state.listOfUnits = payload
        },
        setUnit(state, payload) {
            state.unit = Number(payload)
        },
        setFundingAmount(state, payload) {
            state.fundingAmount = Number(payload)
        }
    },
    actions: {},
    getters: {
        selectedUnit(state) {
            if (!state.listOfUnits) return null
            return state.listOfUnits.filter(obj => Number(obj.Nid) === state.unit)[0]
        },
        unit_name(state, getters) {
            if (getters.selectedUnit) return getters.selectedUnit.title
            return ''
        },
        purchaseCost(state, getters) {
            if (getters.selectedUnit) {
                return parseFloat(getters.selectedUnit.cost_to_own)
            }
            return null
        },
        payableAmount(state, getters) {
          let payableAmt = ( (2/100) * getters.purchaseCost)
                return  parseFloat(payableAmt)
        },
        remainPayCost(state, getters) {
            if (getters.purchaseCost && getters.payableAmount) {
                return getters.purchaseCost - getters.payableAmount
            }
            return null
        },
        otherCost(state, getters) {
            if (getters.selectedUnit) {
                return parseFloat(getters.selectedUnit.actual_price) * 0.04
            }
            return null
        },
        location(state) {
            if (state.propertyData) {
                return {
                    lat: Number(state.propertyData['latitude']),
                    lng: Number(state.propertyData['longitude'])
                }
            }
            return null
        },
        hasLocation(state) {
            if (state.propertyData) {
                return (
                    state.propertyData['latitude'].trim().length &&
                    state.propertyData['longitude'].trim().length
                )
            }
            return null
        },
        propertyGrowthReportData(state) {
            if (!state.propertyData ||
                !state.propertyData.hasOwnProperty('property_growth_report_data')
            ) {
                return []
            }

            const propertyGrowthReportData =
                state.propertyData.property_growth_report_data

            // process growth percentage
            return propertyGrowthReportData.map((arr, i) => {
                if (i == 0) {
                    // header
                    return [...arr, null]
                } else if (i == 1) {
                    // first row
                    return [...arr, null]
                }

                const currentPrice = parseInt(arr[4].replace(/,/g, ''))
                const prevPrice = parseInt(
                    propertyGrowthReportData[i - 1][4].replace(/,/g, '')
                )
                const growthPercent = ((currentPrice - prevPrice) /
                    prevPrice *
                    100).toFixed(2)
                return [...arr, growthPercent]
            })
        },
        hasPropertyGrowthReportData(_, getters) {
            return (
                getters.propertyGrowthReportData &&
                getters.propertyGrowthReportData.length
            )
        },
        actionType(state) {
            if (!state.act) return null
            else if (state.act == 'buy') {
                return 'buy'
            } else if (state.act == 'fund') {
                return 'fund'
            }
            return null
        },
        propertyBuyLeft(state, getters) {
            const {
                propertyData
            } = state
            const {
                actionType
            } = getters

            if (actionType !== 'buy') return null

            let currentDate = new Date()
            currentDate = currentDate.getTime()
            let showdate = new Date(propertyData['expiry-date-buy'])
            showdate = showdate.getTime()

            return Math.floor((showdate - currentDate) / (24 * 60 * 60 * 1000))
        },
        propertyFundLeft(state, getters) {
            const {
                propertyData
            } = state
            const {
                actionType
            } = getters

            if (actionType !== 'fund') return null

            let currentDate = new Date()
            currentDate = currentDate.getTime()
            let showdate = new Date(propertyData['expiry-date-fund'])
            showdate = showdate.getTime()

            return Math.floor((showdate - currentDate) / (24 * 60 * 60 * 1000))
        },
        propertyStatusTxt(_, getters) {
            const {
                actionType
            } = getters
            if (actionType === 'buy') {
                return 'Open for Buying'
            } else if (actionType === 'fund') {
                return 'Buying Closed. Now Funding'
            }
            return 'Closed'
        }
    }
})

 

Sidebarbuy.vue file

<template>
  <div id="sidebar">
    <div class="widget-box">
      <PropertyHead />
      <BuyFundDataRow :borderBottom="1">
        <template slot="label">
          Pay to Own
        </template>
        <template slot="value">
          RM {{ formatPrice(this.purchaseCost) }}
        </template>
      </BuyFundDataRow>

      <BuyFundDataRow :borderBottom="1">
        <template slot="label">
          Transaction Cost
        </template>
        <template slot="value">
          0
        </template>
      </BuyFundDataRow>

      <BuyFundDataRow :borderBottom="1">
        <template slot="label">
          Total Cost
        </template>
        <template slot="value">
          RM {{ formatPrice(this.purchaseCost) }}
        </template>
      </BuyFundDataRow>

      <BuyFundDataRow :borderBottom="1">
        <template slot="label">
          <b>Payable Now</b>
        </template>
        <template slot="value">
          <b>RM {{ formatPrice(this.payableAmount) }}</b>
        </template>
      </BuyFundDataRow>

      <BuyFundDataRow>
        <template slot="label">
          Remaining Left To Pay
        </template>
        <template slot="value">
          RM {{ formatPrice(this.remainPayCost) }}
        </template>
      </BuyFundDataRow>

      <p class="text-center m-t-20 m-b-40">
        Once the administration fee is received, we will proceed to reserve your unit for you. Please note that this is on a first-come-first-served basis and FundMyHome does not guarantee availability of your unit of choice. If your unit is not available, you may either choose another unit or get a full refund.
      </p>
      <p class="text-center m-t-20 m-b-40">
        We will send an email to your registered email address, once the unit is successfully reserved. From then on, you will have 1 week to sign the purchase agreements and other legal documents at our office or show gallery. Failure to do so within the stipulated time period may result in your reservation cancelled and the administration fee forfeited.
      </p>
      <p class="text-center m-t-20 m-b-40">
        Our consultant will call you within 3 business days to provide more information. If you did not receive a call, please contact us at the number provided below.
      </p>
      <NeedHelp />
    </div>
  </div>
</template>
<script>
import PropertyHead from './sub/PropertyHead';
import BuyFundDataRow from './sub/BuyFundDataRow';
import BuyFundDataRowEmphasis from './sub/BuyFundDataRowEmphasis';
import NeedHelp from './sub/NeedHelp';
import { mapGetters, mapState } from 'vuex';

export default {
  components: {
    PropertyHead,
    BuyFundDataRow,
    BuyFundDataRowEmphasis,
    NeedHelp,
  },
  computed: {
    ...mapGetters(['selectedUnit', 'purchaseCost', 'remainPayCost', 'otherCost', 'payableAmount']),
    ...mapState([]),
  },
  props: {
    length: {
      type: Number,
    },
  },
};
</script>

<style lang="scss" scoped>
.img-header {
  height: 100px;
  background-position: center;
  background-size: cover;
}
</style>

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...