天天看點

vuex的簡單使用

使用了 vue-lic腳手架(我不說得很理論,我就說得很通俗)

在store檔案下面寫成(index.js是加載全部)

下面是 modules檔案下的wallet.js代碼

export default {
    state: {
        projects: []
    },
    getters: {
        saleProducts: (state) => {     // 這邊是查詢出來(vue檔案那邊是通路這個的)
            console.log(state.projects)
            return state.projects
        }
    },
    mutations: {
        reducePrice: (state, src) => {  // 這邊把擷取到的資料進行指派
            state.projects = src
        }
    },
    actions: {
        saveForm: ({commit}, src) => {    
// 擷取VUE那邊接口的資料,然後送出到mutations裡面的reducePrice
                commit('reducePrice', src)
    } 
  }      

這是index.js

import Vue from 'vue'
import Vuex from 'vuex'
import wallet from './modules/wallet' // 錢包

Vue.use(Vuex)

export default new Vuex.Store({
    strict: true,
    modules: {
        wallet
    }
})      

vue 這塊使用 (隻能截圖大概出來)

html

<div class="list-li-balancepay" v-for="(list, index) in saleProducts" @click="jumpDetails(list.id)">
        <div class="list-li-left">
            <strong>{{list.title}}</strong><br />
            <span style="color:#aaa;font-size:12px;">{{list.created_at}}</span>
        </div>
        <div class="list-li-right">
            <strong>{{list.change_amount}}</strong>
        </div>
    </div>
</div>      

js

export default {
        created() {
            this.request()
            console.log(1)
        },
        mounted: function() {
            console.log(2)
        },
        activated: function() {
            console.log(3)
        },
        deactivated: function() {
            console.log(4)
        },
        methods: {
            request() {
//                console.log(this.$store.getters.saleProducts)
//                console.log(this.$store.dispatch('saveForm', this.$store.state.user))
                    this.loading = true
                    this.$http.post('xxxxxxxxxxxxxxxxxxxxxxxxx', {},
                        (res) => {
                            if (is.object(res)) { 
                                if (res.status === 'succ') {  
                                   // actions裡面的saceForm方法 傳接口資料過去(那邊接受指派)
                                    this.$store.dispatch('saveForm', res.data.list)
                                } else {
                                    this.$router.push({path: '/login'})
                                }
                            } else {
                                this.$toast.show('加載失敗')
                            }
                        }, (data) => {
                            this.$toast.show('請求資料失敗')
                        })
                }   
            }
        },
        computed: {
            wallet() {
                return this.$store.state.projects // 這個是直接查詢 state裡面的projects這樣為空
            },            
           saleProducts() { 
               return this.$store.getters.saleProducts // 這個是查詢getters 得到接口的資料
           }