'Vuejs onMounted gets executed just 1 time

I have the following problem. In my vue app i am using vue router too

Looks like this:

<div>
   <router-view />
</div>

My problem is: I use the hook onMounted in my router page. But it just gets executed 1x. When i leave the page and come back to it it does not work anymore, the onMounted does not get triggered. Why is this?

<template>
  <div>
    <p>Dashboard</p>
    <div>
      <canvas height="200" ref="chartdiv"></canvas>
    </div>

    <div>
      <p>image</p>
      <input type="file" @change="upload" />
    </div>
  </div>
</template>
<script lang="ts">
import { onBeforeMount, onMounted, ref } from "vue";
import { Chart, registerables } from "chart.js";
import { Storage } from "aws-amplify";
import store from "@/store";
Chart.register(...registerables);
export default {
  setup() {
    onBeforeMount(() => {
      store.commit("SET_LAYOUT", "dashboardLayout");
    });
    let file = ref("");
    let chartdiv = ref<any>(null);
    let chart = ref<any>();
    onMounted(() => {
      let ctx = chartdiv.value.getContext("2d");
      console.log("mounted");
      chart.value = new Chart(ctx, {
        type: "line",
        data: {
          labels: [
            "12:00",
            "12:15",
            "12:30",
            "12:45",
            "13:00",
            "13:15",
            "13:30",
            "13:45",
          ],
          datasets: [
            {
              label: "Cubic interpolation (monotone)",
              data: [10, 20, 40, 30, 10, -10, -30, -20],
              borderColor: "",
              fill: false,
              cubicInterpolationMode: "monotone",
              tension: 0.4,
            },
          ],
        },
        options: {
          maintainAspectRatio: false,
        },
      });
    });

    function sleep(ms: number) {
      return new Promise((res) => setTimeout(res, ms));
    }
    async function upload(e: any) {
      let [file] = e.target.files;
      try {
        await Storage.put(file.name, file);
      } catch (err) {
        console.log(err);
      }
    }

    return { chartdiv, chart, file, sleep, upload };
  },
};
</script>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source