[Vuejs]-Can't get v-model work with Composition API and Vuex

0👍

First, I don’t know which tutorial you read. But to me, the problem is here:

const modelStartDateProxy = computed({
    get: () => store.state.modelStartDate,
    set: (newDate) => store.commit("modelStartDateMutation", newDate)
})

const modelStartDate = store.state.modelStartDate
  1. The snippet
const modelStartDateProxy = computed({
    get: () => store.state.modelStartDate,
    set: (newDate) => store.commit("modelStartDateMutation", newDate)
})

is weird to me.

  1. Duplicate of store.state.modelStartDate. DRY.

  2. <p>{{ modelStartDate }}</p> render data from const modelStartDate = store.state.modelStartDate. But the data was only assign once. So the new value was not render on input was changed.
    Solution:

const modelStartDate = computed(() => store.state.modelStartDate);

You can take a look at this playground.

0👍

The html element input returns a string: "YYYY-MM-DD". Therefore you need the syntax new Date(value)

Take a look at this playground

<template>
  <label>Model start date</label>
  <input type="date" v-model="modelStartDateProxy" />
  <p>{{ modelStartDateProxy }}</p>
</template>

<script>
import { store } from './store.js' //mock-up store
import { ref, computed } from 'vue'
export default {
  setup() {
    const modelStartDateProxy = computed({
      get: () => store.state.modelStartDate,
      set: (newDate) => store.commit(newDate) // Use real Vuex syntax
    })
    return { modelStartDateProxy }
  }
}
</script>
//Mock-up Store (not real vuex)
import {reactive} from 'vue'
export const store = reactive({
  state: {
    modelStartDate: new Date(2022, 0, 3)
  },
  commit: (value) => store.state.modelStartDate = new Date(value) // new Date(value)
})

Leave a comment