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 得到接口的数据
           }


你可能感兴趣的:(技术(javascript))