Skip to content

17. Project [vuejs-15]: Using the [Vuex] plugin

The [vuejs-15] project builds on the [vuejs-14] project by using a reactive [session] object generated by [Vuex]. The project structure is as follows:

Image

17.1. Installing the [vuex] dependency

Image

17.2. The [./session.js] script

The [session] object becomes the following:


// vuex plugin
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
 
// the session is a Vuex store
const session = new Vuex.Store({
  state: {
    // simulation table
    lignes: []
  },
  mutations: {
    // simulation list generation
    generateLignes(state) {
      // eslint-disable-next-line no-console
      console.log("mutation generateLignes");
      // on initialise [state.lignes]
      state.lignes =
        [
          { id: 3, marié: "oui", enfants: 2, salaire: 35000, impôt: 1200 },
          { id: 5, marié: "non", enfants: 2, salaire: 35000, impôt: 1900 },
          { id: 7, marié: "non", enfants: 0, salaire: 30000, impôt: 2000 }
        ];
      // eslint-disable-next-line no-console
      console.log(state.lignes);
    },
    // delete line n° index
    deleteLigne(state, index) {
      // eslint-disable-next-line no-console
      console.log("mutation deleteLigne");
      // delete line n° [index]
      state.lignes.splice(index, 1);
    }
  }
});
// export object [session]
export default session;

Comments

  • lines 2-4: integrate the [Vuex] plugin into the [Vue] framework;
  • line 7: the session becomes an object of type [Vuex.Store];
  • lines 8-11: the [state] property contains the shared state of the [Vue] application. This property will be accessible to all components of the application. Here we share the [lignes] simulation array (line 10);
  • lines 12–35: the property [mutations] contains the methods that modify the content of the object [state];
  • lines 14–26: the property [generateLignes] is a function that generates an initial value for the property [state.lignes]. Here, it accepts [state] as a parameter. Lines 18–23: The property [state.lignes] is initialized;
  • Lines 28–35: The property [deleteLigne] is a function that removes a row from the array [state.lignes]. Its parameters are:
    • [state], which represents the object from lines 8–11;
    • [index], which is the number of the row to be deleted;
  • the functions of the [mutations] property always accept as their first parameter an object representing the [state] property of line 8. The following parameters are provided by the code calling the mutation;
  • line 37: the object [session] is exported.

Unlike the previous project [vuejs-13], we will not have a plugin here to make the session accessible to components in an attribute [Vue.$session].

17.3. The main script [./main.js]

The main script evolves as follows:


// imports
import Vue from 'vue'
import App from './App.vue'
 
// plugins
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue);
 
// bootstrap
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
 
// session
import session from './session';
 
// configuration
Vue.config.productionTip = false
 
// instantiation project [App]
new Vue({
  name: "app",
  // using Vuex blinds
  store: session,
  render: h => h(App),
}).$mount('#app')

Comments

  • line 14: the session is imported;
  • line 23: it is passed to the main view in an attribute named [store] (this is required). Thanks to the [Vuex] plugin, this attribute then becomes available to all components in an attribute named [Vue.$store]. We are therefore in a configuration very similar to that of the previous project: where in a component we accessed the session via the notation [this.$session], we will now access it via the notation [this.$store];

17.4. The main view [App]

The main view [App] changes as follows:


<template>
  <div class="container">
    <b-card>
      <!-- message -->
      <b-alert show variant="success" align="center">
        <h4>[vuejs-14] : utilisation du plugin [Vuex]</h4>
      </b-alert>
      <!-- table HTML -->
      <Table />
    </b-card>
  </div>
</template>
 
<script>
import Table from "./components/Table";
export default {
  // name
  name: "app",
  // components
  components: {
    Table
  },
  // life cycle
  created() {
    // simulation table generation
    this.$store.commit("generateLignes");
  }
};
</script>

Comments

  • line 9: the [App] view uses the [Table] component but no longer receives events from it, thanks to the fact that the [Vuex] store is reactive;
  • lines 24–27: The [created] method is executed immediately after the creation of the [App] component. Within this method, the mutation named [generateLignes] is executed, which generates an initial value for the simulation array. Note the specific syntax of the statement. Recall that the notation [this.$store] refers to the property [store] of the view instantiated in [main.js]:

// instantiation view [App]
new Vue({
  name: "app",
  // using Vuex blinds
  store: session,
  render: h => h(App),
}).$mount('#app')

The notation [this.$store] therefore refers to the object [session]. We then write [this.$store.commit("generateLignes")] to execute the mutation named [generateLignes]. This mutation is a function;

17.5. The component [Table]

The component [Table] evolves as follows:


<template>
  <div>
    <!-- empty list -->
    <template v-if="lignes.length==0">
      <b-alert show variant="warning">
        <h4>Votre liste de simulations est vide</h4>
      </b-alert>
      <!-- reload button-->
      <b-button variant="primary" @click="rechargerListe">Recharger la liste</b-button>
    </template>
    <!-- non-empty list-->
    <template v-if="lignes.length!=0">
      <b-alert show variant="primary" v-if="lignes.length==0">
        <h4>Liste de vos simulations</h4>
      </b-alert>
      <!-- simulation table -->
      <b-table striped hover responsive :items="lignes" :fields="fields">
        <template v-slot:cell(action)="row">
          <b-button variant="link" @click="supprimerLigne(row.index)">Supprimer</b-button>
        </template>
      </b-table>
    </template>
  </div>
</template>
 
<script>
export default {
  // calculated state
  computed: {
    lignes() {
      return this.$store.state.lignes;
    }
  },
  // inner state
  data() {
    return {
      fields: [
        { label: "#", key: "id" },
        { label: "Marié", key: "marié" },
        { label: "Nombre d'enfants", key: "enfants" },
        { label: "Salaire", key: "salaire" },
        { label: "Impôt", key: "impôt" },
        { label: "", key: "action" }
      ]
    };
  },
  // methods
  methods: {
    supprimerLigne(index) {
      // eslint-disable-next-line
      console.log("Table supprimerLigne", index);
      // delete the line
      this.$store.commit("deleteLigne", index);
    },
    // reload displayed list
    rechargerListe() {
      // eslint-disable-next-line
      console.log("Table rechargerListe");
      // the list of simulations is generated
      this.$store.commit("generateLignes");
    }
  }
};
</script>

Comments

  • The [template] in lines 1–24 remains unchanged;
  • lines 30–32: the calculated property [lignes] now uses [store] from [Vuex];
  • Lines 49-54: To delete a row from the HTML table, we use the [deleteLigne] mutation of [store] from [Vuex]. The [index] number of the row to be deleted (row 53) is passed as a parameter;
  • lines 56–61: To reload the HTML table with a new list, we use the mutation [generateLignes] of [store] from [Vuex];

17.6. Conclusion

The attributes [Vue.$session] of project [vuejs-13] and [Vue.$store] of project [vuejs-15] are very similar. They serve the same purpose: to share information between views. The advantage of the [store] object is that it is reactive, whereas the [session] object is not. However, the [vuejs-14] project demonstrated that it was easy to make the [session] object reactive by duplicating it in the reactive properties of the views.