vuex mapGetters


1、vuex 配置

//vuex的配置 //注意Store是大寫
const store = new Vuex.Store({ //數據保存
 state: { show: false, count: 0, list: [1, 5, 8, 10, 30, 50] }, mutations: { increase(state, n = 1) { state.count += n; }, decrease(state, n = 1) { state.count -= n; }, switch_dialog (state) { // 這里的state對應着上面這個state
      state.show = state.show ? false : true
      // 你還可以在這里執行其他的操作改變state
 } }, getters: { filteredList: state => { return state.list.filter(item => item < 31); } }, actions:{ asyncIncrease(context){ context.commit('increase'); }, switch_dialog123 (context) { // 這里的context和我們使用的$store擁有相同的對象和方法
      context.commit('switch_dialog') // 你還可以在這里觸發其他的mutations方法
 } } });

2、mapGetters使用

<template>
    <div> {{count}} <button @click="handleIncrease">+5</button>
        <button @click="handleAsyncIncrease">-5</button> {{filteredList}}
        <button @click="handleRouter">跳轉到 HelloWorld3</button>
        <button @click="showRouter">展示路由</button>
    </div>
</template>

<script> import { mapState } from 'vuex' import { mapGetters } from 'vuex' export default { name: 'HelloWorld2', computed: { // count(){
            // return this.$store.state.count;
            // },
 // filteredList() { // return this.$store.getters.filteredList; // },
 ...mapState({ count: state => state.count }), // 使用對象展開運算符將 getter 混入 computed 對象中
 ...mapGetters([ 'filteredList' ]) }, methods: { handleIncrease() { this.$store.commit('increase', 5); }, handleDecrease() { this.$store.commit('decrease', 5); }, handleAsyncIncrease() { this.$store.dispatch('asyncIncrease'); }, handleRouter() { this.$router.push('/HelloWorld3'); }, showRouter() { console.log(this.$router); console.log(this.$router.push); } } }; </script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM