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

HighCharts fails to display on Polymer webpage

I am working on a project that involves using Polymer alongside HighCharts. Here is the code I have implemented: HTML : <div class="container" layout vertical center> <paper-shadow z="1" class="span-shadow"> <post-card id ...

An async awaitCurrentBlock() function encountered an unexpected identifier while executing my JavaScript file

Encountering a problem while trying to execute my compile.js file using node compile.js. Here's my code: const async = require('asyncawait/async'); const await = require('asyncawait/await'); const HDWalletProvider = require(&apos ...

Is there a way to enforce mandatory fields on material-table?

During my current project, I am utilizing a material-table interface to perform CRUD operations. I am interested in finding out if there is a way to make certain fields required when necessary. Despite my research efforts yielding minimal results, I have ...

Determine the week number based on a specified starting day for the week

If I have a custom week start day other than Monday, how should the getWeekNumber() prototype for the Date class be modified? Here is the existing code for calculating the ISO Week Number: Date.prototype.getWeekNumber = function() { // Create a dupli ...

Concealing numerous tables depending on the visibility conditions of subordinate tables

I have the following HTML code which includes multiple parent tables, each with a specific class assigned to it: <table class="customFormTable block"> Within these parent tables, there are child tables structured like this: <table id="elementTa ...

Issues with MySQL not functioning properly when using Promise.All in a Node.js environment

When it comes to running multiple mysql queries asynchronously in express node.js, MySQL works well with simple callbacks. However, I wanted to take it a step further by using async await with promise.all. I also experimented with promise.allSettled, but u ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...

Seeking assistance with basic Javascript/Jquery for Ajax on Rails 3 - can anyone help?

I've been diving into JavaScript and hit a roadblock. At the moment, I have a very basic gallery/image application. My goal is to create a functionality where clicking on an image will lead the user to a URL stored in my model data using AJAX. Additi ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...

Is it possible to combine multiple jQuery selectors for one command?

I need some help with jQuery commands. I have two similar commands, but not exactly the same. Here are the commands: $("#abc > .className1 > .className2 > .className3"); $("#pqr > .className1 > .className2 > .className3"); Is there a w ...

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Having trouble choosing a dropdown value with ng-model; the first item keeps showing up as blank when selected

When I attempt to select a dropdown value inside an AngularJS function by setting the value to the ng-model, the dropdown initially shows a blank value selected. Below is my HTML code: <select class="pulldown" ng-model="test" ng-options="obj as obj.des ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Can someone explain the process of adding a JavaScript state variable from one React component so that it can be utilized in other components?

In my Home.js component, I handle user sign up to the API and login. After receiving the token from the authorization header in the response, I save it in the state variable 'token'. This token is crucial for accessing the API in other component ...

How can I use JQuery to sum up the numbers within div elements?

Is there a way to automatically number the generated blocks? For example, the first block would display "1", the second "2" and so on. Below is my current code. Simply input the desired number of blocks in the input field. <!DOCTYPE html> <html ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...