Search code examples
javascriptvue.jsfrontendv-modelvue-directives

How can I access my Vue component's data property using a string as it's property name in a v-model directive?


The same way I'm able to access an object's property using bracket notation by utilizing a string naming the property. For example

const foo = {
 "bar[foobar]": "hello world"
}

foo["bar[foobar]"] // "hello world"

How can I do the same in a Vue SFC (Single File Component), where I have a data property named "bar[foobar]" and want to bind it to an input's value giving the v-model directive the value "bar[foobar]"?

<template>
 <input v-model="bar[foobar]" />
</template>
<script>
export default {
  name: 'MyComponent',
  data() {
    return {
     "bar[foobar]": "hello world"
    }
  }
}
</script>

I tried providing the v-model directive as such v-model='{{ 'bar[foobar]' }}' but that didnt't work either, or v-model="this['bar[foobar]']"


Solution

  • Ideally you'd just rename the data property but if you can't then you can access it via $data:

    <input v-model="$data['bar[foobar]']">