Binding a UI element with a Vuex store

1.6k views Asked by At

I'm trying to bind a UI element (a single-line textbox or 'input' element) with a Vuex store. This fiddle has the code.

When the SearchResult component is visible, it auto-updates -- see the GIF below, where Lisp or Prolog is typed. That's not what I'd like to happen. What I'd really like to do is decouple the UI state (i.e. the value of the textbox) from the model's state, so that if I type Lisp and press Search, the SearchResult component updates itself.

Ideally I'd like to bind the textbox with a variable that's not in the store, but also add some code to observe changes to the store, so that any changes to the store are reflected in the UI.

I read the forms handling documentation for Vuex but wasn't very clear about the best way to get this done. Please could anyone help? I'm new to SPAs so I'm sure there's a better way of getting this done.

Result of running the above fiddle

1

There are 1 answers

3
Saurabh On BEST ANSWER

I think the approach you have used is the general approach if you want to use a store variable in input. Given that you want to decouple the UI variable with the model's state(Why?), you can do following:

  1. Have a local variable in that vue instace
  2. use that local variable with v-model
  3. put a watch on state variable, if state variable changes, change local variable.
  4. set state variable on button press, or some other way like onblur event

Here are relevant JS changes:

const app = new Vue({
    router,
    el: '#app',
    data: {
      localQuery: ''
    },
    computed: {
        query: {
            get () { return store.state.query },
            set (v) { store.commit('setquery', v) }
        }
    },
    methods: {
        s1: function () {
            console.log('app.s1 this.query: ' + this.query);
            this.query = this.localQuery
            router.push({ name: 'qpath', params: { query: this.query }});
        }
    },
    watch:{
       query: function (newVal) {
                    this.localQuery = newVal
       }
    }
})

see updated fiddle here.