2

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]']"

tony19
  • 125,647
  • 18
  • 229
  • 307
john-raymon
  • 306
  • 1
  • 7
  • 20

1 Answers1

2

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]']">
skirtle
  • 27,868
  • 4
  • 42
  • 57
  • Thank you! I'd like to keep the data property in sync with what's being returned from https://Commercejs.com on validation errors. So if I'd like to watch a property I'd use strings to set method/function property name within the watch object on the instance? `watch: { "bar[foobar]": function(old, new) { } }` – john-raymon Aug 20 '19 at 19:45
  • 1
    @john-raymon You can only use simple, dotted paths with `watch`. For anything more complicated you'll need to call the `$watch` method manually. See https://vuejs.org/v2/api/#vm-watch – skirtle Aug 20 '19 at 20:44