The role of vuexCopy the code

Get the book information rendered to the page and calculate the total price store/index.js by sending an Ajax requestCopy the code
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {

  },
  mutations: {

  },
  getters: {

  },
  actions: {

  },
  modules: {
    books: {
      namespaced: true,
      state: { pir: [] },
      getters: {
        totalPrice: function (state) {
          let sum = 0
          state.pir.forEach(item => {
            sum += item.price
          })
          return sum
        }
      },
      mutations: {
        setBooks (state, newBooks) {
          state.pir = newBooks
        }
      },
      actions: {
        add: function (context) {
          axios({
            url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books'
          }).then(res => {
            context.commit("setBooks", res.data.data)
          })
        }
      },
    }
  }
})
export default store
Copy the code
                                main.js
Copy the code
import Vue from 'vue' import App from './App.vue' import store from './store' Vue.config.productionTip = false new Vue({  store, render: h => h(App), }).$mount('#app')Copy the code
                               APP.vue
Copy the code
<template> <div id="app"> <p v-for="(item, The index) in $store. State. Books. The pir ": the key =" index "> {{item. The name}}, {{item. Price}} < / p > total: {{ $store.getters["books/totalPrice"] }} </div> </template> <script> export default { created () { this.$store.dispatch('books/add') } } </script> <style> </style>Copy the code