Vue - How to scope variables within template

Viewed 2530

Can I scope data somehow within a component's template?

For example, if I have the following code:

data() {
    a: {test: 'Test A'},
    b: {test: 'Test B'}
}

Currently in the template I have to do

<div class="a">{{ a.test }}</div>
<div class="b">{{ b.test }}</div>

Is there any way I can scope data per element? For example, something like:

<div :scope="a">{{ test }}</div><!-- This prints 'Test A' -->
<div :scope="b">{{ test }}</div><!-- This prints 'Test B' -->

I do know that I can extract each item to a component, however, I was wondering if there is a way to do that within the same template? As it does not have own logic etc. so I don't want to extract it to a separate component just to scope the variable. However, it can get tedious repeating the same variable name many times.

For example, I have a form to create a new item, which has a number of inputs. I keep them under a variable (for example) newItem, which looks like

newItem: {
    input1: "",
    input2: "",
    input3: null,
    input4: false,
    // etc...
}

And in the template I would like to do

<div :scope="newItem">
    <input v-model="input1"/>
    <!-- etc.. --->
</div>

Instead of

<input v-model="newItem.input1"/>
<!--- etc... --->
1 Answers

NO.

There's no such a way to do. And also v-model needs to be specified to the particular data else it will not work. Otherwise, we can think of v-for.

Related