Search code examples
vue.jsvue-componentnuxt.jsvuexemit

How to emit a Vue event into state


How can I set an event value emitted from a component straight to the state in the data property instead of just calling a function first and setting it after e.g

<Input
  id="firstname"
  type="text"
  v-model="user.firstname"
  required
  p="p-2
  md:p-4"
  class="mt-2"
  errorText="First name field cannot be empty"
  :validation="user.firstname.length === 0"
  @valid="checkFirstName"
/>

But I want to set the value coming directly from @valid to a key in my state


Solution

  • The value comes in as $event and you can set it directly to a data property:

    @valid="name = $event"
    

    Since your question is tagged Vuex, maybe you want to call a mutation:

    @valid="$store.commit('SET_NAME', $event)"
    

    I don't see a good reason for that when you could commit from the child. If the question is about altering Vuex state without a mutation, no that's a violation and shouldn't be done.

    Here's a demo:

    Vue.component('child', {
      template: `<button @click="$emit('valid', 'myname')">click me</button>`
    })
    
    new Vue({
      el: "#app",
      data: () => ({
        name: ''
      })
    });
    <div id="app">
      Name: {{ name }}<br>
      <child @valid="name = $event"></child>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>