4

Is there a way to create nested components in vue.js?

<newform>
    <field></field>
    <field></field>
    <field></field>
    <field></field>
    <submit></submit>
</newform>

In my case, only the newform component is rendered, but not the nested components.

My Code:

app.js

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
Vue.config.debug = true;
Vue.config.async = true;
 
/**
 * The base Vue Instance
 */
new Vue({
    el: '#app',
    components: {
        'new-form': require('./components/form')
    }
});
 

form.js

module.exports = {
    template: "Hallo Welt",     
    props: ['url', 'method'],    
    components: {
        'field': require('./field')
    },    
    created: function() {
        console.log("Form Component created");
    }
}
 
 

field.js

module.exports = {    
    template: 'Ein Text feld',    
    props: ['name', 'type'],   
    create: function() {
        console.log("Field Component created");
    }
}

Link to code sample

1
  • Can you add the actual DOM that does get rendered? Also, the "create" function on field.js should be "created". Commented Jun 30, 2015 at 0:26

3 Answers 3

4

The functionality you are describing is called a slot in Vue. It allows you to nest content inside a component you're including by using a special <slot> tag in its template. Here's an example.

Looking at that link, it's important to note the components aren't in the parent-child relationship you're trying to imply. Your form doesn't need to specify field under its components. It has a slot and it doesn't care what will show up in it.

Both form and field should be specified under components in your app.js, that's where all the heavy lifting is done and that's where both components are included.

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

Comments

0

You can use components, like this: http://jsfiddle.net/hajkrupo/5/

<body>
    <encapsulated-component inline-template>
        <header>
            <cart-status></cart-status>
        </header>
        <cart></cart>
        <item some-prop="1"></item>
        <item some-prop="2"></item>
        <item some-prop="3"></item>
    </encapsulated-component>
</body>

Comments

0

You want to render <field> in <newform>, so you need to show the field template in newform template. Like this

form.js

module.exports = {    
  template: 'Ein Text feld<slot></slot>',    
  props: ['name', 'type'],   
  create: function() {
    console.log("Field Component created");
  }
}

Another point is to require field.js in app.js not form.js.

Here is the example http://www.webpackbin.com/4k9vxYrCl.

Hopes to help you.

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.