0
votes

I am trying to create a dynamic 'quick input' form with Vue.

A simple text input that has a dynamic data key so that I can change what I'm submitting to axios. I couldn't figure out how to get a dynamic key name coming from a prop eg

data() {
  return {
  DYNAMIC-NAME-FROM-PROP: value
  }
}

So I've got a values: {} bit of data that gets filled by the props instead. The code below achieves everything EXCEPT pre-rendering the existing value. See the comments next to v-model in the tempate:

<template>
  <div class="relative">
    <input
      type="text"
      v-model="values[fieldName]" // This is not rendering on load
      // v-model="values[this.$props.field]" -> 'this' is null error @input
      @keydown.enter.prevent="submit"
    />
  </div>
</template>

<script>
export default {
  props: ["userId", "field", "preFill"],
  data() {
    return {
      values: {},
      fieldName: this.$props.field,
    };
  },
  mounted() {
    this.values[this.$props.field] = this.$props.preFill;
  },
  methods: {
    submit() {
      axios.post(`/admin/${this.userId}/update`, this.values).then(response => {
        // success
      });
    }
  }
};
</script>

Am I going about this completely wrong?

Or am I 'nearly there' and just need to fix the v-model render issue?

1

1 Answers

0
votes

To set a dynamic key name on an object in javascript, it turns out you can use square brackets, as in:

{
 [keyName] : value
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

So my code is fixed by simply passing the prop as the key in the axios call:

submit() {
      axios
        .post(`/admin/${this.userId}/update`, {
          [this.$props.field]: this.value
        })
        .then(response => {
          // we out here
        });
    }