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: {
    // the array of simulations
    lines: []
  },
  mutations: {
    // generate the list of simulations
    generateLines(state) {
      // eslint-disable-next-line no-console
      console.log("generateLines mutation");
      // initialize [state.lines]
      state.lines =
        [
          { id: 3, married: "yes", children: 2, salary: 35000, tax: 1200 },
          { id: 5, married: "no", children: 2, salary: 35000, tax: 1900 },
          { id: 7, married: "no", children: 0, salary: 30000, tax: 2000 }
        ];
      // eslint-disable-next-line no-console
      console.log(state.lines);
    },
    // delete line at index
    deleteLine(state, index) {
      // eslint-disable-next-line no-console
      console.log("deleteLine call");
      // delete line [index]
      state.lines.splice(index, 1);
    }
  }
});
// export the [session] object
export default session;

Comments

  • lines 2-4: we integrate the [Vuex] plugin into the [Vue] framework;
  • line 7: the session becomes a [Vuex.Store] object;
  • 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 array of simulations [lines] (line 10);
  • lines 12–35: the [mutations] property contains the methods that modify the contents of the [state] object;
  • lines 14–26: the [generateLines] property is a function that generates an initial value for the [state.lines] property. Here, it takes [state] as a parameter. Lines 18–23: the [state.lines] property is initialized;
  • lines 28–35: the property [deleteLine] is a function that removes a line from the array [state.lines]. 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 from line 8. The following parameters are provided by the code calling the mutation;
  • line 37: the [session] object is exported.

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

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

// project instantiation [App]
new Vue({
  name: "app",
  // Use Vuex store
  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 [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 [App] view changes as follows:


<template>
  <div class="container">
    <b-card>
      <!-- message -->
      <b-alert show variant="success" align="center">
        <h4>[vuejs-14]: using the [Vuex] plugin</h4>
      </b-alert>
      <!-- HTML table -->
      <Table />
    </b-card>
  </div>
</template>

<script>
import Table from "./components/Table";
export default {
  // name
  name: "app",
  // components
  components: {
    Table
  },
  // lifecycle
  created() {
    // generate the simulation table
    this.$store.commit("generateLines");
  }
};
</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 [App] component is created. Within this method, the [generateLines] function is called, which generates an initial value for the simulations array. Note the specific syntax of the statement. Recall that the notation [this.$store] refers to the [store] property of the view instantiated in [main.js]:

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

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

17.5. The [Table] component

The [Table] component evolves as follows:


<template>
  <div>
    <!-- empty list -->
    <template v-if="lines.length==0">
      <b-alert show variant="warning">
        <h4>Your list of simulations is empty</h4>
      </b-alert>
      <!-- reload button -->
      <b-button variant="primary" @click="reloadList">Reload list</b-button>
    </template>
    <!-- non-empty list-->
    <template v-if="lines.length!=0">
      <b-alert show variant="primary" v-if="lignes.length==0">
        <h4>List of your simulations</h4>
      </b-alert>
      <!-- simulation table -->
      <b-table striped hover responsive :items="rows" :fields="fields">
        <template v-slot:cell(action)="row">
          <b-button variant="link" @click="deleteRow(row.index)">Delete</b-button>
        </template>
      </b-table>
    </template>
  </div>
</template>

<script>
export default {
  // computed state
  computed: {
    lines() {
      return this.$store.state.lines;
    }
  },
  // internal state
  data() {
    return {
      fields: [
        { label: "#", key: "id" },
        { label: "Married", key: "married" },
        { label: "Number of children", key: "children" },
        { label: "Salary", key: "salary" },
        { label: "Tax", key: "tax" },
        { label: "", key: "action" }
      ]
    };
  },
  // methods
  methods: {
    deleteLine(index) {
      // eslint-disable-next-line
      console.log("Table deleteRow", index);
      // delete the row
      this.$store.commit("deleteLine", index);
    },
    // reload the displayed list
    reloadList() {
      // eslint-disable-next-line
      console.log("Table reloadList");
      // regenerate the list of simulations
      this.$store.commit("generateLines");
    }
  }
};
</script>

Comments

  • the [template] for lines 1–24 remains unchanged;
  • lines 30–32: the computed property [lignes] now uses the [store] from [Vuex];
  • lines 49-54: to remove a row from the HTML table, we use the [deleteLigne] mutation of the [Vuex] [store]. We pass the [index] number of the row to be removed as a parameter (line 53);
  • lines 56–61: To reload the HTML table with a new list, we use the [generateLines] mutation of the [Vuex] [store];

17.6. Conclusion

The [Vue.$session] attributes in the [vuejs-13] project and the [Vue.$store] attributes in the [vuejs-15] project are very similar. They serve the same purpose: sharing 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 is easy to make the [session] object reactive by duplicating it in the reactive properties of the views.