Using Vue's md-input with Vuex results in data updating in a single direction

My Vue application has an input element connected to a Vuex store like this:

<template>
   <input v-model="this.$store.state.myvalue"/>
</template>

The code in my VueX store/index.js is as follows:

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    myvalue: null
  },
  mutations: {},
  actions: {},
  modules: {}
});

When I update the value of myvalue using Vue devtools, it reflects on the input field. However, when I change the input field value, the state variable remains unchanged. Any idea what mistake I might be making? I am still learning how to work with Vuex in Vue.

Answer №1

While it is not recommended to directly bind vuex state with the view layer, it is advisable to use vuex for handling business logic. If you need to change the state based on user input, you can achieve this through the following methods:

[1] Two-way data binding: Use the v-model directive to bind the state. When the user inputs data, the state will be updated. If the state changes programmatically, the element's value will also be updated and reflected in the DOM.

.vue file

<template>
   <input v-model="$store.state.myvalue"/>
</template>

[2] Manually create two-way data-binding.

.vue file

<template>
   <input :value="getMyValue" @input="handleInput"/>
</template>

<script>
export default {
 methods: {
  handleInput (value) {
   this.$store.commit('UPDATE_MY_VALUE', { value })
  }
 },
 computed: {
  getMyValue () {
   return this.$store.state.myvalue
  }
 }
}
</script>

Store file

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    myvalue: null
  },
  mutations: {
   UPDATE_MY_VALUE (state, { value }) {
    state.myvalue = value
   }
  },
  actions: {},
  modules: {}
});

Answer №2

There seems to be an issue with updating the state variable when changing the value in the input field.

Although the state variable does change, it may not reflect immediately in the Dev tools. You can confirm this by modifying the template as follows:

<template>
  <div>
    <input type="text" v-model="$store.state.myvalue">
    <div>{{ $store.state.myvalue }}</div>
  </div>
</template>

It's worth noting that directly mutating Vuex state like this is generally discouraged. It is recommended to use mutations for state changes as they make tracking changes easier and more structured. Mutations are essentially functions called when a state change is required.

To achieve 2-way data binding against Vuex state, computed properties with getter/setter methods can be utilized. Here's an example:

<template>
  <div>
    <input v-model="myvalue">
    <div>{{ myvalue }}</div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  computed: {
    myvalue: {
      get: function() {
        return this.$store.state.myvalue;
      },
      set: function(value) {
        this.$store.commit("change_myvalue", value);
      }
    }
  }
};
</script>

A corresponding mutation should be defined in your store for this setup to work effectively:

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    myvalue: ""
  },
  mutations: {
      change_myvalue(state, value) {
          state.myvalue = value
      }
  },
  actions: {},
  modules: {}
});

For further information on mutations, you can refer to the documentation here.

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

Ways to modify the color of cells in a table generated from JSON

In developing an HTML table based on JSON data, I have created a university semester map that displays student information including their ID, year, term, and required courses for graduation. While the table is successfully created, I aim to customize the ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

The vertical loading of the post slider is causing some issues compared to the

Every post slider on this website has a unique loading feature where it loads vertically for a brief moment before fully loading. While all the styles load perfectly, it seems that the javascript may be causing this slight delay. Could this be a result of ...

In JavaScript, implement event listeners exclusively on the main container and its immediate child elements

Is there a way to target just the main container and its second child elements for an event? Specifically, targeting id="container" and all elements with class="secondChild" Currently, I have a listener attached to all elements inside ...

An error occurs when attempting to upload an image in cropper js due to a violation of the Content Security Policy directive: "img-src * data:"

I'm currently using cropperjs to crop an image upon uploading click here to see the button Once the image is selected for upload, I encounter this problem The data in blob storage remains intact, but there seems to be an issue after the image is upl ...

button for resetting the zoom in Highcharts

Attempting to manipulate the visibility of the Zoom Button on a highstock chart through x axis zooming with the navigator feature enabled. The default behavior seems to disable the button in this scenario. While there are functions allowing for display, I ...

The iron-session package does not export the path ./next/dist from the package

I am encountering an issue while using iron-session. Below is the code snippet causing the error: import { withIronSessionSsr } from 'iron-session/next/dist'; ... export const getServerSideProps = withIronSessionSsr(async function ({ req, r ...

Having trouble getting Safari to load preflight CORS authentication requests (XHR) in a Vue.js application hosted on Apache?

I've been spending hours researching and trying to debug, but I'm not having any luck. This workflow/request works fine on Chrome, but Safari and Firefox both fail at the OPTIONS preflight request. Safari shows two errors: (!) Failed to load res ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Leverage variables in JavaScript to establish a unique style

function AdjustScale(){ scaleX = window.innerWidth / 1024; scaleY = window.innerHeight / 768; element = document.getElementById("IFM"); element.style.transform = "scale(" + scaleX + ", " + scaleY + ")"; } I'm facing an issue with thi ...

Don't forget to save the toggleClass state to local storage in jQuery so it persists after

It's a challenge to maintain the value of toggleClass after refreshing or reloading the page. I have a structured table where rows toggle visibility when clicked. To preserve these toggle values, I utilized localStorage, but unfortunately, the state i ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

What is the best way to pass the first of two values from Angular to Node.js?

Press the button to retrieve two folderid values. Is there a way to only send the first folderid to the service? Refer to the screenshot below - when clicking on folder-1 (folderid 1230), it opens to reveal four folders. Then, clicking on folder-1-1 (fold ...

Using URL parameters in Node.js applications

I am encountering an issue with my nodejs setup, and I am hoping someone can assist me. My challenge lies in trying to pass a parameter with a specific value to a page.html file, like this: page.html?s=1 However, I am encountering a problem where the pa ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...