How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my state using map actions, resulting in an array of string values.

Now, how do I access this array using mapGetters? Here is the snippet of my code:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info"gt;{{ message }}</h1>
    </div>
  </body>
</template>

<script>
  import moment from "moment";
  import { mapGetters } from "vuex";

  export default {
    name: "Home",
    data() {
      return {
        // message: this.store.state.message
        elementVisible: true
      };
    },
    computed: {
      ...mapGetters(["message", "sec"]),

      ...mapGetters({
        message: "message",
        sec: "sec"
      }),
      createdDate() {
        return moment().format("DD-MM-YYYY");
      },
      createdHours() {
        return moment().format("HH:mm");
      }
    },
    mounted() {
      this.$store.dispatch("SET_MESSAGE");
      this.$store.dispatch("SET_SEC");

      setTimeout(() => (this.elementVisible = false), this.sec);
    }
  };
</script>

My goal is to display the message received from the configuration panel as a clean string within the {{message}} template. The message is currently stored in my state as an array of strings like ["hello", "how are you"]. How can I extract the first value ("hello") and prevent it from being displayed as ["hello"]?

(At present, the entire array is being displayed in the template)

Should I make some changes in my store.js file?

const state = {
  message: [],
  sec: +[]
};
const getters = {
  message: state => {
    return state.message;
  },

  sec: state => {
    return state.sec;
  }
};

const actions = {
  setMessage: ({ commit, state }, inputs) => {
    commit(
      "SET_MESSAGE",
      inputs.map(input => input.message)
    );

    return state.message;
  },

  setSec: ({ commit, state }, inputs) => {
    commit("SET_TIMEOUT", inputs.map(x => x.sec).map(Number));
    console.log(inputs.map(x => x.sec).map(Number));
    return state.sec;
  }
};
const mutations = {
  SET_MESSAGE: (state, newValue) => {
    state.message = newValue;
  },

  SET_TIMEOUT: (state, newSecVal) => {
    state.sec = newSecVal;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

The homepage should display the message and handle the timeout functionality based on the sec value provided. It should continue displaying subsequent values from the array after each timeout duration.

Thank you!

Answer №1

Greetings and salutations on Stack Overflow! The message Array is being properly mapped with mapGetters, but it appears that you are flattening it as a String when inserting it into the template using {{message}}. Due to how template interpolation works, objects are converted to strings, similar to calling Array.toString in this context. To properly display the array elements, you need to iterate through them by utilizing the v-for directive:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info">
        <span v-for="m of message" :key="m">{{m}}</span>
      </h1>
    </div>
  </body>
</template>

If you only require display of the first item, you can directly show it using the following approach:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info">{{message[0] || 'No message'}}</h1>
    </div>
  </body>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Vue Nuxt application returned an error when running npm dev because the new image file

Hey there, I recently added an image to the assets folder and after running npm run dev, my page is not displaying the image. You can check out the image https://i.stack.imgur.com/EczEy.png Here's my code: <div :style="{ backgroundImage: ...

Delaying Ajax request

I've encountered some strange behavior. After the initial ajax call triggered by selecting a city from a dropdown menu, I then have a continuous ajax call on a delay. The first call stores the selected city value in a global variable. $('.sele ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

Is it possible to identify the origin URL of a user using Javascript or AngularJS?

Is it possible to use Angular to detect the origin URL of a user visiting my website in order to perform specific operations later on? ...

Tool designed to analyze the timing of sub requests and methods in Node for benchmarking purposes

For my benchmarking and load testing needs, I initially utilized tools such as Apache Bench, Siege, and benchmark.js. However, these tools only provided me with the overall result or time taken from start to finish of the test. I am now seeking a tool or l ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

Ways to conceal a dynamically generated div upon page load?

I am currently facing a scenario where I need to dynamically create a div. My initial approach was to create it on the document ready event, but the requirement is for it to be displayed only upon selection. The problem I am encountering is that the empty ...

Utilizing JavaScript's Facebook Connect feature on a Ruby on Rails website

My ruby-on-rails web application is in need of integrating "Facebook connect" functionality to enable users to share various activities on Facebook. Are there any Javascript methods I can use for this purpose? Any demos you can suggest? In addition, I wou ...

Nuxt3 introduces Intlify i18n with the requirement "It is necessary to be invoked at the beginning of a `setup` function"

Encountering an issue when attempting to alter the language within a click function. "Uncaught SyntaxError: Must be called at the top of a setup function (at message-compiler.mjs:54:19)". However, changing the language outside of the function ...

Count the occurrences of different fields in a document based on a specified condition

Seeking a way to extract specific values and calculate the frequency of those values in a collection based on a certain key's ID. Consider this example of a single document from a Game Logs collection: { "_id": "5af88940b73b2936dcb6dfdb", "da ...

Guide on initializing a Redux toolkit state with an array of objects or local storage using TypeScript

Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error. Type 'number' is not assignable to type '{ id: string; price: number; ...

Enhancing user experience with dynamically resized Jumbotron images based on screen sizes in HTML

I am experiencing an issue with the jumbotron images on my website where they become increasingly zoomed in as the screen size decreases, and are extremely zoomed in on mobile devices. Is this a normal behavior of jumbotrons? I do understand that the image ...

Innovative ways to design a responsive carousel with Bootstrap

My goal was to create a slider with divisions inside a bootsrap carousel, and here is what I did. However, I am looking for guidance on how to adjust it so that on screens smaller than sm (of bootstrap), there are only two divisions in one carousel, and a ...

The PHP counter conceals the comma upon loading and does not display it permanently

I'm currently working on a PHP counter and encountering an issue with the comma display. I have implemented Number Format in a PHP function to print counter digits with commas every 3 digits, but the comma doesn't remain visible after the page lo ...

Tips for refreshing an html table without affecting the scroll location?

HTML: <div class="html_table"></div> # Within the html body tag. Utilizing Ajax function to retrieve table data. var $html_table= $('.html_table'); function ajaxCallFunction() { $.ajax({ type: 'POST', ...

Are you able to locate <td>s with identical classes using just a portion of the string?

There are multiple classes in the <td>s of my table. I am looking to identify each <td> that contains a specific string. For instance: <table> <tr> <td class="hello there">foo</td> <td class=" ...

Tips on concealing or deactivating the "sort by" input and label for the Vuetify 3 <v-data-table> when in mobile view

Utilizing a vuetify <v-data-table> to display some data : On Mobile: The Code: <v-data-table-server :items-per-page="itemsPerPage" :headers="headers" :items="serverItems" :items-length="totalI ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

Navigate the array and divide the elements into separate values

For a project I need to upload files, wherein the data is organized within an object like [5.76516834507, 50.8474898368], [5.76115833641, 50.8453698247]. The task here is to extract and store the first value as latitude: 5.76516834507 and the second value ...

Header Stability TransitionAndView

I'm not very experienced with JavaScript, so please bear with me. I'm attempting to create a fixed header that transitions to 50% opacity when scrolled down and returns to full opacity (opacity: 1.0) when scrolled back to the top. Here is my cur ...