Vuex v-shaped input not responding

I am trying to explain this as simple as possible. I have something like this. Simple Vue root, Vuex repository, and v-model input inside navbar id.

This input does not respond ... Why ?!

enter image description here

enter image description here

HTML

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

store.js

import Vuex from 'vuex'

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

Vue root

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

new Vue({
  el: '#navbar',
  store,
  computed: {
    test () {
      return this.$store.getters.test
    }
  }
})
+7
source share
4 answers

You are attached to the computed property. To set a value for a computed property, you need to write getand methods set.

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

And in your store

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

Now, when you change the value of the input parameter associated with the test, it will cause a commit to the store, which will update its state.

+22
source

v-model . @input="test" methods:

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

Vuex:

mutations:

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

actions:

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

, @{{test}}

, Vuex: http://codepen.io/anon/pen/gmROQq

+2

You can easily use v-modelwith Vuex (with actions / mutations triggering each change) using my library:

https://github.com/yarsky-tgz/vuex-dot

<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>
+1
source

The property computedis one-way. If you need two-way binding, create an installer as other answers suggest, or use a property instead data.

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

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

But the setter checks the input value better.

0
source

Source: https://habr.com/ru/post/1672123/


All Articles