Vue input not reacting to v-model in Vuex state

I am attempting to simplify the explanation as much as possible. The structure I have includes a basic Vue root, Vuex store, and an input with v-model inside the navbar id.

However, it seems that the input is not reactive... Why is that?

https://i.sstatic.net/v4ukJ.png

https://i.sstatic.net/v4ukJ.png

Snippet of HTML code:

<div id="navbar">
    <h2>@{{ test }}</h2>
    <input v-model="test" />
</div>

store.js content:

import Vuex from 'vuex'

export const store = new Vuex.Store({
  state: {
    test: 'test'
  },
  getters: {
    test (state) {
      return state.test
    }
  }
})

Vue Root setup:

import { store } from './app-store.js'

new Vue({
  el: '#navbar',
  store,
  computed: {
    test () {
      return this.$store.getters.test
    }
  }
})

Answer №1

To assign a value to a computed property, you must define both the get and set methods.

computed:{
    test:{
        get(){ return this.$store.getters.test; },
        set( value ){ this.$store.commit("TEST_COMMIT", value );}
    }
}

In your store file:

mutations:{
    TEST_COMMIT( state, payload ){
        state.test=payload;
    }
}

Now, any changes made to the input linked to the test property will trigger a store commit, updating its state accordingly.

Answer №2

Avoid using v-model in this case. Instead, incorporate @input="test" into your input field and in the methods section:

 test(e){
    this.$store.dispatch('setTest', e.target.value)
 }

Within your Vuex store:

For mutations:

   setTest(state, payload){
      state.test = payload
   },

And for actions:

setTest: (context,val) => {context.commit('setTest', val)},

Your input should now be responsive and you can view the outcome in @{{test}}

To see how I manage user input with Vuex, click here: http://codepen.io/anon/pen/gmROQq

Answer №3

If you want to streamline your use of v-model in combination with Vuex, my library offers a solution:

Check out this library on GitHub for an easy integration.

<template>
  <form>
    <input v-model="name"/>
    <input v-model="email"/>
  </form>
</template>

<script>
  import { takeState } from 'vuex-dot';

  export default {
    computed: {
      ...takeState('user')
        .expose(['name', 'email'])
        .commit('editUser') // payload example: { name: 'Peter'}
        .map()
    }
  }
</script>

Answer №4

Remember, the computed property only allows for one-way binding. If you're looking for two-way binding, consider creating a setter function as suggested in other responses or utilize the data property instead.

import { store } from './app-store.js'

new Vue({
  el: '#navbar',
  store,
  data: function() {
    return { test: this.$store.getters.test };
  }
});

It's worth noting that using a setter can also help in validating input values efficiently.

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

Switching image when hovering with mouse using javascript

I am working on an HTML webpage and trying to make an image change when hovering over a div, but it doesn't seem to be working. Any suggestions? <!doctype html> <html> <head> <meta charset ="UTF-8"/> &l ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

Tips for creating a helper function that returns a promise for a React hook function

So, I have this React functional component that makes use of both the useState and useEffect hooks: import React, { useState, useEffect } from 'react'; import { requestInfo } from './helpers/helpers'; const App = () => { const [pe ...

Using jQuery's sortable functionality to rearrange rows in a table can cause conflicts with Angular's orderBy feature

In the past, my angular app used a table with orderBy to sort rows based on a specific column. By clicking on a table header, the orderBy arguments would change and the list would be sorted according to the values in that column. Now, I am experimenting w ...

What is the best way to obtain the value of a radio button using ajax?

Here is the search button in my PHP file. I am unsure of how to connect the radio button to the JavaScript file. <button id="submit">Search</button> This is the starting point in the JavaScript file var xhr = new XMLHttpRequest(); f ...

Options for a web-based application that can handle multiple currencies

Looking to create a web application with Vue.js and Firebase that allows users to purchase products or services using a payment API like paypal or stripe. I am trying to display the prices of these products in the local currency of each user, but I'm ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

React Hooks findByID method is throwing an error stating that it cannot read the property 'params' because it is undefined

As I dive into learning React hooks, I'm realizing that it's crucial to stay up-to-date with the latest trends in web development. Despite hours of research and tinkering around, I can't seem to wrap my head around some key concepts. The fac ...

Tips for retrieving document body from a script embedded within document.write

I urgently need assistance! I am currently developing an application that retrieves a report from an API, and the JSON response includes HTML content. Unfortunately, due to the JSON format, I cannot directly open this in a new browser window. Within my sc ...

What is the approach for capturing system or website sound using JavaScript?

After creating an online drumkit and guitar player, I am now looking to enhance my website by adding a feature that allows users to record their sessions and download them. Since I am new to web development and familiar only with HTML, CSS, JavaScript, and ...

JQuery UI Dialog not functioning properly as intended, failing to display

Issue: The dialog box is appearing without the buttons being pressed and it does not function as an overlay when activated. Any help would be greatly appreciated. Code: Includes: <script src="js/jquery-1.5.1.min.js"></script> <script src ...

Click on the react item to view more information

I'm brand new to React and I'm exploring the swapi API for the first time. My goal is to retrieve a list of films (movie titles) and then, when a title is clicked on, display the opening crawl from the JSON object. So far, I've been able to ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Issue with Modal functionality in Internet Explorer 9

Check out the URL of a page that functions properly in Firefox, Chrome, and Safari, but is experiencing issues in IE 9. Upon page load, a modal displays a banner. The modal I am using can be found at Although the script appears to be correct, I have not ...

Can the settings of the Firefox browser be modified using a Vue.js application?

I utilized Kerberos for single sign-on (SSO) in my project. However, when making a request from the Vue.js client application to the Kerberos server, it does not work properly in Firefox due to disabled Kerberos support by default. This requires users to m ...

What is the best way to decrease the transparency of the unselected 3D items when clicked on?

I've been thinking about how to adjust the opacity of unselected 3D objects in a scene when one object is clicked. Essentially, I want all other objects to have reduced opacity once a particular object is selected. For example, if one object has an op ...

Increasing and decreasing the display of content using JQuery based on height rather than character count

I'm attempting to create a show more/show less link with a set height of 200px that, when clicked, will reveal the rest of the content. Anything exceeding 200px will be hidden, and there will be a "show more" link to display the remaining text. I&apos ...

Identifying and implementing page language in nextJS: Solving the ReferenceError "window is not defined" issue

I am currently working on developing a website that can automatically detect the user's country and set the language accordingly. In React, I usually achieve this by using window.navigator.language. Here is a snippet of the code: import * as pt from ...

Tips for launching a fresh window and embedding HTML into it with jQuery?

I'm attempting to use JavaScript to open a new window, but the HTML content is not being added: var callScriptText = $('#callScriptText').html(); var url = '/Action/CallScript/?callScript='; // Open the current call script in a n ...