Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Previously we learned that Vuex initiates a request via axios back end, stores the requested data in the Vuex Store, and uses the data in the page through a specific interface call. This article will be requested to the data through the definition of routing, display to the page. Equivalent to the actual project of the user list, the list of goods data display effect.

Preface: What is Vuex and its documentation

Vuex official document: vuex.vuejs.org/zh/

  1. Vuex simultaneously changes data What is stored in mutations is the method of simultaneously changes data
  2. Vuex Asynchronous data modification Action stores the method of asynchronous data modification

The data requested asynchronously by Vuex via AXIOS is presented to the page

Vuex initiates a request through the axios back end and stores the requested data in Vuex Store. Here, the data obtained asynchronously is displayed during access by defining a route:

1. Define a route

We defined two data objects, Users and goods, so we defined two routes corresponding to two pages

// SRC /router/index.js Route definition module
import Vue from 'vue'
import Router from 'vue-router'
/// import the page template
import Users from '@/components/Users'
import Goods from '@/components/Goods'

Vue.use(Router)

export default new Router({
  mode: 'history'.routes: [{path: '/'.redirect: { name: 'users' }, // Redirect to route whose name is Users
    },
    {
      path: '/users'.name: 'Users'.component: Users,
    },
    {
      path: '/Goods'.name: 'Goods'.component: Goods,
    },
  ],
})
Copy the code

2. After the route is defined, write the corresponding page template

Define two pages in SRC/Components: users. vue and goods. vue

  1. Then use the data in the template:

/// Users.vue

<template>
  <div class="users">
    <ul>
      <li v-for="(user, index) in userLists" :key="user._id">{{ user._id }}: {{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'Users'.computed: {
      // Computed attributes are performed immediately after the HTML DOM is loaded!
      userLists() {
        return this.$store.state.users
      },
    },
    destroyed() {
      console.log('component destroyed')}},</script>
Copy the code

/// Goods.vue

<template>
  <div class="users">
    <ul>
      <li v-for="(good, index) in goodLists" :key="good._id">{{ good._id }}: {{ good.name }}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'Users'.computed: {
      goodLists() {
        return this.$store.state.goods
      },
    },
    destroyed() {
      console.log('component destroyed')}},</script>
Copy the code

Refer to official documentation

  • Vuex official document: vuex.vuejs.org/zh/