Connect an input in VueJS to a VueX store state value

As someone new to VueJS, I'm currently working on a VueJS application that provides information about a Github user. For example, you can check out details for .

I've set up a store using VueX, but I'm facing an issue with updating the value entered by the user in the input field. The "inputValue" always remains as "" (its default value) even when I type something in the input field.

I've attempted the following implementation:

<template>
  <div class="input">
    <input
      type="text"
      :placeholder="placeholder"
      v-model="inputValue"
      @change="setInputValue(inputValue)"
      @keyup.enter="getResult(inputValue)"
    />
    <input type="submit" @click="getResult(inputValue)" />
  </div>
</template>

<script>
import store from "../store";

export default {
  name: "Input",
  props: {
    placeholder: String,
  },
  computed: {
    inputValue: () => store.state.inputValue,
  },
  methods: {
    setInputValue: (payload) => {
      store.commit("setInputValue", payload);
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

and also this within `store/index.js`:

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    inputValue: "",
  },
  getters: {
    getInputValue(state) {
      return state.inputValue;
    }
  },
  mutations: {
    setInputValue(state, payload) {
      console.log("setInputValue");
      console.log("payload ", payload);
      state.inputValue = payload;
    },
  },
});

Answer №1

As stated in the documentation of vuex on form handling, the recommended approach is:

  :value="inputValue"
      @change="setInputValue"

Additionally, you should define the following method:

 methods: {
    setInputValue: (event) => {
      store.commit("setInputValue", event.target.value);
    }
  }

Answer №2

If you're looking for an elegant way to connect vuex with a component, utilizing computed properties is the way to go. To implement this approach, modify the code as shown below:

 <input
      type="text"
      :placeholder="placeholder"
      v-model="inputValue"
      @keyup.enter="getResult(inputValue)"
    />

To make it work seamlessly, update your computed properties by replacing `inputValue` with the following code snippet.

computed: {
    inputValue: {
      set(val){
        this.$store.commit(‘mutationName’, val)
      },
      get() {
        return this.$store.stateName
      }
    }
}

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

Employing regular expressions within Notepad++ to insert whole numbers into img src within table elements

I have a large table filled with numerous items that require individual images to be added. Let's take a look at the code snippet below. <tr><td><img src=".jpg" width=100 height=100/></td></tr> Although I could manually ...

Accessing fields from other sources in ng-repeat can be accomplished by utilizing special syntax within the ng-repeat directive

I have a unique challenge where I need to utilize the firstkey from one AngularJS model, firstcollection, as an index value in another collection called anothercollention. Essentially, I want to iterate over the values in anothercollention based on the k ...

What is the best way to pass value to a URL in a React JS application?

Is there a way to properly use history.push in React to push text to the URL route manually? I am trying to achieve this in my onChange method for an input field: function Header(props) { return ( <div> <input type="radio" onChan ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...

How come require() doesn't resolve the image path when passed as a prop in NuxtJS?

I am encountering an issue in my NuxtJS project where a component is not displaying an image correctly. Despite passing the image path directly to :src="imageAddress", it does not resolve nor throw an error. I attempted using the path inside requ ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

How to insert a new document into a MongoDB collection with Mongoose

Consider a scenario where my existing collection called fruits is structured as follows: {"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7} {"_id" : ObjectId("abc...."), " ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

The Vue CLI is failing to pick up SocketIO events

Working on a Chat Application using VueCLI and Nodejs, I have set up proxy connections and everything seems to be functioning well. However, my VueCLI component is not listening to emit events from the server. The "sockets" object in the vue component is ...

Learn the process of developing a web client application using Node.js and NPM similar to the AngularJS tutorial

I am new to nodejs, npm and angularjs. I recently explored the angularjs tutorial project available at https://github.com/angular/angular-phonecat.git. This project has been really interesting for me as it demonstrates how easy it is to manage modules wi ...

Simply close by clicking outside using basic vanilla JavaScript

I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area. Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only b ...

AJAX is not displaying the expected output

Seeking help on calling a PHP method from JavaScript to query a database and integrate the results into JS functionality. The current 'console.log(output)' in my Ajax returns: "array (size=1) 'action' => string 'getResults&apos ...

Issue: Unhandled TypeError: Problem detected when calling storage.set(object items, optional function callback) in a Chrome Extension

Attempting to create my first Chrome extension, focusing on blocking access to specific websites like Facebook or Instagram. Using code to close tabs if the blocked sites are accessed. In a separate HTML file, providing users with two radio button options ...

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

How to implement a scrollbar for tables using Angular

How can I implement a vertical scroll bar only for the table body in my Angular code? I want the scroll bar to exclude the header rows. Since all rows are generated by ng-repeat, I am unsure how to add overflow style specifically for the table body. Here ...

What are the steps to install node.js on hosting servers like Hostinger, JustHost, and others?

Recently, I've been diving into the world of Node.js. While I have some experience with PHP, I've found that most hosting services already have a PHP interpreter installed, making it easy to work with. However, I'm now trying to figure out i ...

Prevent validation on a particular input field with JQuery validator and Bootstrap

Is there a way to use JQuery validator to validate an entire form except for a specific input? Here is an example code snippet showing how this can be done: jQuery.validator.setDefaults({ debug: true, success: "valid" }); ...

How can I iterate through the lines of a JSON file using javascript?

I am currently working with JSON data and need to extract specific information based on an ID. For example, if the ID is 1, I want to retrieve details like service1 and version 1.0. I am looking to create a loop that will iterate through each line of data ...