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 = {
  // list of simulations
  getLines() {
    return this._lines;
  },
  // Generate the list of simulations
  generateLines() {
    this._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 }
      ]
  },
  // delete row #index
  deleteRow(index) {
    this._rows.splice(index, 1);
  }
}
// export the [session] object
export default session;

15.2. The [./plugins/pluginSession] plugin

The [pluginSession] script is as follows:


export default {
  install(Vue, session) {
    // adds a [$session] property to the Vue class
    Object.defineProperty(Vue.prototype, '$session', {
      // When Vue.$session is referenced, we return the second parameter [session] of the [install] method
      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

// instantiate project [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]: Updating a component, sharing data with a session</h4>
      </b-alert>
      <!-- HTML table -->
      <Table @updateTable="updateTable" :key="versionTable"/>
    </b-card>
  </div>
</template>

<script>
import Table from "./components/Table";
export default {
  // name
  name: "app",
  // components
  components: {
    Table
  },
  // internal state
  data() {
    return {
      // table version
      versionTable: 1
    };
  },

  // methods
  methods: {
    updateTable() {
      // eslint-disable-next-line
      console.log("App updateTable");
      // increment table version
      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="rows.length==0">
      <b-alert show variant="warning">
        <h4>Your simulation list 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.$session.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: {
    removeLine(index) {
      // eslint-disable-next-line
      console.log("Table deleteLine", index);
      // delete the row
      this.$session.deleteLine(index);
      // ask the parent component to update the view
      this.$emit("updateTable");
    },
    // reload the displayed list
    reloadList() {
      // eslint-disable-next-line
      console.log("Table reloadList");
      // regenerate the list of simulations
      this.$session.generateLines();
      // ask the parent component to update the view
      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.