What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself?

I've attempted it like this but seem to be making a mistake somewhere.

HTML

<f7-list-input
  label="Username"
  name="username"
  placeholder="Username"
  type="text"
  :value="newUserName"
  @input="username = $event.target.value"
  required validate
  pattern="[3-9a-zA-Zа-яА-ЯёЁ]+"
  v-model="saveUserName"
/>

SCRIPT

export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    signIn() {
      const self = this;
      const app = self.$f7;
      const router = self.$f7router;
      router.back();
      app.dialog.alert(`Username: ${self.username}<br>Password: ${self.password}`, () => {
        router.back();
      });
    },
    saveUserName(){
        this.$store.commit(saveName);
    }
  },
  computed:{
     userName(){
         return this.$store.state.newUserName;
     }
  }
};

STORE

export default new Vuex.Store({
    state:{
        userNameStor: 'newUserName',
        userPasswordStor:''
    },
    mutations:{
        saveName(state){
            userNameStor:newUserName;
            return newUserName;
        }
    }
});

Answer №1

To understand the complete functionality, let's discuss it in detail followed by some code snippets.

The input is located within the template section of a component.

In addition to the template, the component also contains a script section that triggers code based on template events. The component code can initiate mutations, which are utilized to make changes to the state stored in the store.

Here is the flow for storing information:

1/ Component template event => 2/ Component script code => 3/ Execution of mutation on the store

On the other side, you have:

State => mapMutation within the computed property of the component => component template.

Within the component script, you can map a store value to a computed property of the component using the mapMutations helper. Subsequently, this field is mapped in the template from the computed property of the component.

1 - Your template @input represents the event triggered when there is an input change due to user action. :value denotes the programmatically defined value of the input. v-model serves as a shortcut for using both @input and :value simultaneously. Avoid using it with :value and @input at the same time.

Here is a basic template example:

<f7-list-input
  type="text"
  :value="username"
  @input="changeUsername"
/>

In the script section, simply link the changeUsername method to the mutation (using mapMutation) and define a computed property named username, which maps to the username stored in the store (via mapState).

import {mapState, mapMutations} from "vuex"

export default {
  methods:{
     ...mapMutations({
    changeUsername:"saveName"
  },
  computed:{
     ...mapState({
        username:state=>state.username
    }),
  }
};

For more information, refer to Vue documentation on mutations and state

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

Creating a Vue JS project that utilizes both HTTP and HTTPS URLs for improved security

I'm currently utilizing Vue JS with the webpack template and dev mode. I have a question regarding how to configure my server to allow for both HTTPS and HTTP protocols simultaneously. I understand that enabling HTTPS can be done by simply adding "ht ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

Unable to retrieve coverage report using rewire and cross-env

My challenge lies in obtaining the coverage report using nyc, which works flawlessly without the cross-env plugin. cross-env NODE_ENV=test nyc mocha --ui bdd --reporter spec --colors --require babel-core/register tests --recursive When executing this com ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

How to refresh the javascript cache in Laravel 5.8

I developed a company profile website using Laravel 5.8 and Vue.js to make it reactive, although it's not a single page application (SPA), we can refer to it as a hybrid. The website runs smoothly locally; however, after modifying the JavaScript code ...

Using jQuery to smoothly scroll to a specific class name

I am faced with an HTML code snippet that looks like this: <div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div> My intention is to use jQuery to scroll to the game number 456 as shown below. var contain ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Guide on waiting for an asynchronous function in the constructor in JavaScript

In the process of creating a JS class, I encounter a situation where I need to call wasmFunc in the constructor and store its output in this.val. However, since wasmFunc comes from a WebAssembly file, it is necessary to execute an async function called loa ...

Two-column layout with consistent height vertically, but varying heights on individual rows

By using JavaScript, I am able to ensure that two columns have equal height. The left column contains user input which can vary in length, causing some columns to have more content than others. My current issue is that there are multiple rows instead of ju ...

javascript how to trigger a change or input event when handling a paste event

I have successfully overridden the paste event on the document object, but now I want to trigger the onchange, oninput, and other input events in the event handler for the paste event. document.addEventListener('paste', function (e) { ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

Is the parameter retrieval method correct or erroneous?

I am looking to retrieve data by clicking a link. Here are the links available: <a class="note" id="' . $data["p_id"] . '" value="1" href="javascript:void(0)">+1</a> <a class="note" id="' . $data["p_id"] . '" value="-1" ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...

Converting JSON arrays to integers from strings in JavaScript: A step-by-step guide

When my application receives a Json string from the server (written in Java), I am faced with an issue when retrieving the data in JavaScript. The current format of the data looks like this: var data = [{"value":"3","label": "17 hr"}, {"value":"2", "labe ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

Different ways to modify the underline and label color in Material-UI's <Select/> component

A while ago, I came across this useful demo that helped me change the colors of input fields. Here is the link: https://stackblitz.com/edit/material-ui-custom-outline-color Now, I'm on a quest to find a similar demo for customizing the color of selec ...

Discover the power of React Meteor, where reactive props and inner state work together

I am working with a component that utilizes the draft-js library for text editing. import React, { Component } from 'react' import { EditorState, convertToRaw } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' imp ...