“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

vuex

Vuex is a state management plug-in in VUE to implement unified state management globally. There is only one state tree in a project where all data is stored

Unidirectional data flow

The picture is very important, to understand, can go to the official website for detailed explanation

The data flows in one direction. The View dispatches an action via dispatch, changes the state, and re-renders the view after the data changes

Anything that has to do with server-side interactions is put in actions, such as interfaces

Mutation – commit actions – dispatch – interface

How to use Vuex

npm i vuex Install plugins
Copy the code
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


Copy the code

== Part of demo ==

1. This demo uses the vue directory created earlier, so there are a lot of things that are not the focus of this article, and some configurations that are not described here but are not written, 2. Since getting the interface data is using AXIos, you also need to type the command line to install AXIos: NPM I axios 3. Create a store directory in the SRC source file and create an index.js file in it for file splitting

4. File run NPM Run serve to open localhost:8080 or NPM run build and double click in the packaged dist file to open index.html

/ SRC /store/index.js/SRC /main.js/SRC/app.vue/SRC /pages/ home.vue

/src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 1.list: [].pages: 1.totals: 1.page: 1.cartCount: 0
  },
  mutations: {
    plus(state, step = 1) {
      state.count += step
    },
    reduce(state) {
      state.count--
    },
    loadDataEnd(state, payload) {
      // payload payload = paypay.movies; // payload = paypay.movies; // Payload = paypay.movies; // Payload = paypay.movies; // Payload = paypay.movies
      this.state.list = [...state.list, ...payload.movies]
      state.pages = payload.pages
      state.totals = payload.totals
      state.page++
    },
    buy(state) {
      this.state.cartCount++
    }
  },
  actions: {
    loadData({ commit }, { page }) {
      axios
        .get('http://localhost:3000/api/v1/m', {
          params: {
            page
          }
        })
        .then(res= > {
          console.log(res.data)
          commit('loadDataEnd', res.data)
        })
    }
  }
})

export default store

Copy the code

/src/main.js

import Vue from 'vue'
// import Vuex from 'vuex'
import App from './App.vue'
import router from './router'

import store from './store'

Vue.config.productionTip = false
// Vue.use(Vuex)

/* const store = new Vuex.Store({ state: { count: 1 }, mutations: { plus(state, step = 1) { state.count += step }, reduce(state) { state.count-- } } }) */

new Vue({
  router,
  store,// store: store, all future components can use $store to obtain vuex data
  render: h= > h(App)
}).$mount('#app')

Copy the code

/ SRC/app.vue where does the shopping cart increase the number of purchases

<template>
  <div id="app" class="container">
    <div class="header">-{{$store.state.count}}</div>
    <router-view class="content"></router-view>
    <ul class="footer">
      <li class="active">
        <i class="fa fa-home"></i>
        <span>Home page</span>
      </li>
      <li>
        <i class="fa fa-fire"></i>
        <span>selling</span>
      </li>
      <li style="position:relative;">
        <span class="dot" v-show="$store.state.cartCount>0">{{$store.state.cartCount}}</span>
        <i class="fa fa-shopping-cart"></i>
        <span>The shopping cart</span>
      </li>
      <li>
        <i class="fa fa-user"></i>
        <span>my</span>
      </li>
    </ul>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
}
html.body..container {
  width: 100%;
  height: 100%;
}
.container {
  display: flex;
  flex-direction: column;
}
.container .header {
  height: 40px;
  text-align: center;
  background: rgb(14.184.184);
  line-height: 40px;
  color: white;
  font-weight: 900;
}
.container .content {
  flex: 1;
  overflow: auto;
}
.container .footer {
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: rgb(14.184.184);
  color: white;
}
ul li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
ul li i {
  font-size: 1.6 rem;
}
ul li span {
  font-size: 0.6 rem;
}
ul li.active {
  color: black;
  font-weight: 900;
}
img {
  max-width: 100%;
}
.dot {
  background: palevioletred;
  color: white;
  width: 1rem;
  height: 1rem;
  border-radius: 50%;
  position: absolute;
  padding: 0.2 rem;
  top: -10px;
  left: 16px;
  text-align: center;
}
</style>

Copy the code

/src/pages/Home.vue

<template>
  <div class="home">
    <h1>{{ $store.state.count }}</h1>
    <button @click="countAdd">Count + 1</button>
    <button @click="countAddStep(5)">Count + 5</button>
    <button @click="countReduce">Count - 1</button>
    <ul>
      <li v-for="item in $store.state.list" :key="item._id">
        {{ item.title }}-----------
        <button @click="buyHandle">buy</button>
      </li>
    </ul>
    <keep-alive>
      <button v-show="isShowLoadMore" @click="loaData">Load the data</button>
    </keep-alive>

    <! <img: SRC ="img" Alt ="img" />
    <! -- <img alt="Vue logo" src=".. PNG "/> <img: SRC ="img" Alt =" baw" /> <HelloWorld MSG ="Welcome to Your vue.js App" />-->
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
// import xx from '.. /assets/images/4.jpeg'

export default {
  name: 'Home'.components: {
    // HelloWorld
  },
  data() {
    return {
      // img: require('.. /assets/images/4.jpeg')
      // img: xx,
      isShowLoadMore: true}},methods: {
    countAdd() {
      // The commit operation passes two parameters, type payload
      // type indicates the name in mutation
      // Payload indicates a parameter
      this.$store.commit('plus')},countAddStep(buchang) {
      this.$store.commit('plus', buchang)
    },
    countReduce() {
      this.$store.commit('reduce')},loaData() {
    	// We can't write <= because they can be equal. If we write equal, the if will be invalid
      if (this.$store.state.pages < this.$store.state.page) {
        this.isShowLoadMore = false
        return
      }
      this.$store.dispatch('loadData', { page: this.$store.state.page })
    },
    buyHandle() {
      this.$store.commit('buy')}}}</script>
<style scoped>
img {
  max-width: 100%;
}
ul {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
}
ul li {
  flex: 1;
  flex-direction: row;
  height: 50px;
  display: flex;
  padding: 0.5 rem 0.3 rem;
}
</style>

Copy the code

` `

= = demo comment = =

/src/store/index.js

// Do module splitting
import Vue from 'vue'
/ / introduce vuex
import Vuex from 'vuex'
import axios from 'axios'

/ / use veux
Vue.use(Vuex)

// Create a global vuex instance
const store = new Vuex.Store({
  // Represents global state data
  // All future components can use $store to get data from vuex
  state: {
    count: 1.list: []./ / data
    pages: 1./ / the total number of pages
    totals: 0./ / the total number
    page: 1.// The current page number
    cartCount: 0
  },
  // This is where all data changes are made.
  // a mutation can only be committed (triggered) by commit
  mutations: {
    Parameter 2 can accept parameters sent by commit
    plus(state, step = 1) {
      state.count += step
    },
    reduce(state) {
      state.count--
    },
    loadDataEnd(state, payload) {
      // If there are no pages, just fetch it like this
      // state.list = payload
      // If there is pagination done to load more effects needed:
      state.list = [...state.list, ...payload.products]
      state.pages = payload.pages
      state.totals = payload.totalCount
      // click a page number plus one to load more effects
      state.page++
    },
    buy(state) {
      state.cartCount++
    }
  },
  // How do I distribute actions? Distributed at Home
  // dispatch actions Actions interact with the server
  actions: {
    // Accept two arguments
    // Context indicates that the context is an object containing all the data in vuEX, such as commit
    // The two parameter indicates the data to be received
    // Destruct the assignment directly when receiving the parameter
    loadData({ commit }, { page }) {
      // console.log(context)
      // console.log(payload)
      // get the commit
      // const { commit } = context
      axios
        .get('http://localhost:3009/api/v1/products', {
          params: {
            page // page: page // upload the page number to the server
          }
        })
        .then((res) = > {
          console.log(res.data)
          // Bring up the data by committing a mutations change state data
          commit('loadDataEnd', res.data)
        })
    }
  }
})

export default store

Copy the code