1

I am using Vue.js V1 and want to take some JSON like this:

{ "class": "foo bar", "max-length": 25 }

And map it to an element so something like this:

<input type="text" {{ json }} />

And that renders as:

<input type="text" class="foo bar" max-length="25" />

I have tried this with a method <input type="text" {{ convertJSON(json) }} /> where convertJSON creates a string from the JSON. This doesn't work. When I transpile with it vueify it gives me the error “Found camel case attribute”.

Is this possible with Vue?

EDIT: I want to do it without having to go through each attribute manually; I already know how to bind them. I wondered if it was possible to do it dynamically. I suspect it isn't but wanted to check.

Thanks.

4 Answers 4

3

You can pass an object of attributes to v-bind. This works in v1 and v2.

In your case, assuming json is the JSON object:

<input type="text" v-bind="json" />

Here's an example fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

This syntax will most probably fail - vue is run after html is rendered - you will already have major html problems here because it will try to interpret {{ json }} as html attributes.

However you can always bind you data

<div v-bind:class="myJson.class" v-bind:max-length="myJson['max-length']">
...

If you are really interest in binding everything with one json you can simply create a component that wraps a basic input like

<template>
    <inputv-bind:class="data.class" v-bind:max-length="data['max-length']">
</template>

And define a single prop here

// .. component definition
props: ['data'], 
// ..

Comments

0

You can create a custom directive that takes the json as a parameter and automatically turns each key-value pair into an arrtibute on the element.

1 Comment

This is exactly what v-bind does when you pass it an object, no need for a custom directive.
0

Just use v-bind.

For example

<input type="text" v-bind:class=[myClass] v-bind:maxlength=[myLength] />

data: {
  myClass: 'foo',
  myLength: 25
}

```

Live Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.