Reputation:
It's not working: https://jsfiddle.net/2ouxsuLh/
var myAwesomeComponent = Vue.component({
template: '<div><slot></slot></div>',
data: function () {
return {
myAwesomeData: 'Message'
}
}
});
new Vue({
el: '#app',
template: '<my-awesome-component>{{ myAwesomeData }}</my-awesome-component>',
components: {
myAwesomeComponent: myAwesomeComponent
}
});
It's happening because myAwesomeData isn't defined in parent component, and we can't use component's variables with .
Instead of this, we need to create our own component and pass it inside my-awesome-component like this: https://jsfiddle.net/simplesmiler/5p420nbe/
But it's overhead, isn't it?
For example, in angular we can do this: http://jsfiddle.net/ADukg/9609/ It's much simplier.
We can do something like this in Vue?
Upvotes: 6
Views: 3657
Reputation: 43881
You can use scoped slots to approximate your Angular example. The child defines a slot
in its template, and as an attribute of the slot
tag, it defines data that will be available to the parent. The parent passes a template in as the slot filler. The template can refer to the data defined by the child through the scope
attribute.
var myAwesomeComponent = {
template: '<div><slot myAwesomeData="Directive Message"></slot></div>'
};
new Vue({
el: '#app',
components: {
test: myAwesomeComponent
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="app">
<test>
<template scope="props">
{{ props.myAwesomeData }}
</template>
</test>
</div>
Upvotes: 1