Karl Wong
Karl Wong

Reputation: 605

Inserting a v-model into a vuejs element

I'm trying to do something like this, do not know how to describe in technical term, can't seem to find a solution for this.

<div id="app">
   <input type="text" v-model="model1" />
</div>

<div>
  <div id="model2">ABCDEFG</div>
  <input type="text" />
</div>

<script>
new Vue({
        el: '#app',
        data: {'model1': 'value'},
...
...
...
});
</script>

How can i add model2 element into my #app data? I do not want to wrap my model2 inside of #app because it is a partial, and is shared throughout the application. Is there a way i can inject it on a particular page when it is needed?

Upvotes: 0

Views: 41

Answers (1)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

You can make that model2 div a separate component o that it can be reused anywhere you want like this:

html

<div id="app">
   <input type="text" v-model="model1" />
   <reusable-comp></reusable-comp>
</div>

script

<script>

var reusableComp = {
    template: `
        <div id="model2">
          <div>ABCDEFG</div>
          <input type="text" />
        </div>
    `,
    data(){
        return{
           //reactive properties for this component 
        }
    }
}


new Vue({
        el: '#app',
        data: {'model1': 'value'},
        components:{
            reusableComp
        }
...
...
...
});
</script> 

You can also register that as a global component like this

Vue,.component('reusableComp',{ //...options })`

See docs for more on components

Upvotes: 2

Related Questions