Skip to content

15. Project [vuejs-13]: Updating a component, using a session

The [vuejs-13] project builds on the [vuejs-12] project by introducing the following change: the array displayed by the HTML table is defined in a [session] object known to all components. This is therefore a way to share information between components. This concept is directly inspired by the web session. We use the plugin method to make this shared object available in a [Vue.$session] attribute.

The project directory structure is as follows:

Image

15.1. The [session] object

The [session] object shared by all components is defined in the [./session.js] script:


const session = {
  // liste des simulations
  get lignes() {
    return this._lignes;
  },
  // génération de la liste des simulations
  generateLignes() {
    this._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 }
      ]
  },
  // suppression ligne n° index
  deleteLigne(index) {
    this._lignes.splice(index, 1);
  }
}
// export de l'objet [session]
export default session;

15.2. The [./plugins/pluginSession] plugin

The [pluginSession] script is as follows:


export default {
  install(Vue, session) {
    // ajoute une propriété [$session] à la classe vue
    Object.defineProperty(Vue.prototype, '$session', {
      // lorsque Vue.$session est référencé, on rend le 2ième paramètre [session] de la méthode [install]
      get: () => session,
    })
  }
}
  • line 4: the shared object [session] will be available in the [$session] property of all components;

15.3. The main script [main.js]

The main script [main.js] is 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';
import pluginSession from './plugins/pluginSession'
Vue.use(pluginSession, session)
 
// configuration
Vue.config.productionTip = false
 
// instanciation projet [App]
new Vue({
  name: "app",
  render: h => h(App),
}).$mount('#app')
  • lines 14–16: the [pluginSession] plugin is integrated into the [Vue.js] framework;
  • after line 16, the [$session] attribute is available to all components;

15.4. The main view [App]

The [App] view is now as follows:


<template>
  <div class="container">
    <b-card>
      <!-- message -->
      <b-alert show variant="success" align="center">
        <h4>[vuejs-13] : mise à jour d'un composant, partage des données avec une session</h4>
      </b-alert>
      <!-- table HTML -->
      <Table @updateTable="updateTable" :key="versionTable"/>
    </b-card>
  </div>
</template>
 
<script>
import Table from "./components/Table";
export default {
  // nom
  name: "app",
  // composants
  components: {
    Table
  },
  // état interne
  data() {
    return {
      // version table
      versionTable: 1
    };
  },
 
  // méthodes
  methods: {
    updateTable() {
      // eslint-disable-next-line
      console.log("App updateTable");
      // incrément version table
      this.versionTable++;
    }
  }
};
</script>

Comments

  • The [App] view no longer manages the table displayed by the [Table] component on line 9;
  • line 9: the [Table] component emits the [updateTable] event, which requests that the [Table] component be re-rendered. One way to do this is to use the [:key] attribute. We give this attribute a mutable value. Every time it is modified, the [Table] component is re-rendered;
  • Line 9: The value of the [:key] attribute is the [versionTable] attribute on line 27. The [updateTable] method (lines 33–38) is responsible for regenerating the [Table] component from line 9. To do this, the method increments the value of the [:key] attribute of the [Table] component on line 37. The [Table] component is then automatically regenerated;

15.5. The [Table] component

The [Table] component 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 {
  // état calculé
  computed: {
    lignes() {
      return this.$session.lignes;
    }
  },
  // état interne
  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" }
      ]
    };
  },
  // méthodes
  methods: {
    supprimerLigne(index) {
      // eslint-disable-next-line
      console.log("Table supprimerLigne", index);
      // on supprime la ligne
      this.$session.deleteLigne(index);
      // on demande au composant parent de mettre à jour la vue
      this.$emit("updateTable");
    },
    // rechargement de la liste affichée
    rechargerListe() {
      // eslint-disable-next-line
      console.log("Table rechargerListe");
      // on régènère la liste des simulations
      this.$session.generateLignes();
      // on demande au composant parent de mettre à jour la vue
      this.$emit("updateTable");
    }
  }
};
</script>

Comments:

  • the [rows] attribute (lines 4, 12, 17) is no longer a parameter set by the parent component but a computed attribute of the [Table] component (lines 30–32). [rows] is therefore the array [$session.rows] (line 31);
  • Lines 49–56: The [deleteRow] method removes a row from the [$session.rows] array. By default, this deletion does not change the display of the HTML table. This is because the elements of [$session] are not reactive: changes to them are not reflected in the components that use them. For this reason, the [Table] component asks its parent to regenerate it using the [updateTable] event (line 55). We saw that the parent component would then increment the [:key] attribute of the [Table] component to force its regeneration;
  • lines 58–65: the [reloadList] method asks the [$session] object to regenerate the [$session.rows] array. For the same reason as before, this modification of [$session.list] does not, by default, change the display of the HTML table. For this reason, the [Table] component asks its parent to regenerate it using the [updateTable] event (line 64).

15.6. Running the project

Image

We get the same results as in the [vuejs-12] project.