How to pass data to a component template - javascript

Currently I'm defining several component template(s) within a single vue component. I've defined some as strings, however it makes it somewhat incomprehensible if it gets more complex. So instead I'm making it return a separate component as a template. However I'm not sure how to pass data to the component.
This is a sample of the current approach for one of my component templates within my vue component. It's returning the template as a string and renders the html.
progessTemplate: function () {
return {
template: ('progessTemplate', {
template: `
<div id="myProgress" class="pbar">
<div id="myBar" :class="barColor" :style="{'width': width}">
<div id="label" class="barlabel" v-html=width ></div>
</div>
</div>`,
data: function () {
return { data: {} };
},
computed: {
width: function () {
if (this.data.SLA <= 20) {
this.data.SLA += 20;
}
return this.data.SLA + '%';
},
barColor: function(){
if(this.data.SLA > 60 && this.data.SLA <= 80){
return 'bar progressWarning';
}else if(this.data.SLA > 80){
return 'bar progressUrgent';
}
}
}
})
}
},
I'd like to avoid this approach and call a separate file instead.
I import the component into my vue file
import QueryDetailTemplate from '../../ej2/queryDetailTemplate';
and within my main vue file I have this function 'QueryDetailTemplate':
export default{
data(){
return{
data: [...],
QueryDetailTemplate: function(){
return {
template: QueryDetailTemplate,
props:{
test: 'Hello World',
},
};
},//end of QueryDetailTemplate
}//end of data
...
}
In my QueryDetailTemplate.vue this is my code:
<template>
<div>
Heyy {{test}} //undefined
</div>
</template>
<script>
export default{
props: ['test'],
created(){
console.log(this.test); //shows undefined
}
}
</script>
It renders the 'Heyy' that's hardcoded but it doesn't get the 'test' prop.
Appreciate any pointers

I'm not quite sure what you're trying to achieve but...you should be specifying the component as a component like so:
export default{
components: {
QueryDetailTemplate
},
data(){
return{
data: [...],
}
}
OR if you want to import it asynchronously:
import Vue from 'vue'
export default {
methods: {
import() {
Vue.component(componentName, () => import(`./${componentName}.vue`));
}
}
}
And then you can render it in main:
<query-detail-template
test='Hello World'>
</query-detail-template>

Related

Vue, dynamically import template

I want to be able to swap out a template for a component based on a data property, or a prop. Is this possible?
This is my idea, however this doesn't work of course.
./index.vue
export default {
props:{
},
template: import(`./Themes/Templates/${this.template}`),
data: function() {
return {
template: 'Default'
}
},
./Themes/Templates/Default.vue
<div>
<p>Default template</p>
</div>
Currently getting this error:
invalid template option:[object Module]
Use component that vue.js provide:
<template>
<component :is="myComp"></component>
</template>
...
// You need to import all the possible components
import CompOne from '/CompOne.vue';
import CompTwo from '/CompTwo.vue'
props:{
myComp: {
default: 'comp-one',
type: String,
},
},
...
Try require("./Themes/Templates/Default.vue")
Update:
In Default.vue:
...
export default {
name: "Default"
}
...
and in index.vue:
...
template: this.temp,
data() {
const { Default } = import("./Themes/Templates/Default.vue");
return {
temp: Default
}
}
...

Why is my 'data' param in a Vue.js Storybook not overriding the data of the component?

I have the following component, meant to minimally reproduce this issue:
<template>
<div>
foo is: {{foo}}
</div>
</template>
<script>
export default {
name: 'demo',
data: function() {
return {
foo: 'bar',
}
},
}
</script>
<style scoped>
</style>
With a corresponding story:
import { storiesOf } from '#storybook/vue';
import fetchMock from 'fetch-mock';
import Demo from '../src/components/Demo';
storiesOf('Demo', module)
.add('default', () => {
return {
components: {Demo},
template: '<div style="width: 500px"><Demo/></div>',
}
})
.add('foo is baz', () => {
return {
components: {Demo},
template: '<div style="width: 500px"><Demo/></div>',
data: () => ({
foo: 'baz',
}),
}
});
As you can see from this screenshot, the value of "foo" in the component doesn't update to "baz", even though I have specified data as a function in the return value from the story. What is going wrong?

Vue component using computed property of the mixin

I have a simple component that uses mixin that's shared across multiple components with similar functionality.
When I run it I seem to be getting
Property or method "activeClass" is not defined on the instance but
referenced during render.
Here's my mixin
<script>
export default {
data() {
return {
opened: false,
identity: ''
}
},
computed: {
activeClass() {
return {
active: this.opened
};
}
},
created() {
window.EventHandler.listen(this.identity + '-toggled', opened => this.opened = opened);
},
methods: {
toggle() {
window.EventHandler.fire('toggle-' + this.identity);
}
}
}
</script>
and my component
<template>
<span class="pointer" :class="activeClass" #click="toggle"><i class="fas fa-search"></i></span>
</template>
<script>
import Trigger from '../../mixins/Trigger';
export default {
data() {
return {
mixins: [Trigger],
data() {
return {
identity: 'language'
}
}
}
}
}
</script>
For some reason I cannot seem to be able to access activeClass computed property from within the component. Any idea why is this happening?
Try to move mixin to components main scope. Not in data function rerurn

Working with dynamic components in vue.js

I have a simple application which need to render 2 components dynamically.
Component A - needs to have onClick event.
Component B - needs to have onChange event.
How is it possible to dynamically attach different events to component A/B?
<template>
<component v-bind:is="currentView">
</component>
</template>
<script>
import A from '../components/a.vue'
import B from '../components/b.vue'
export default {
data: function () {
return {
currentView: A
}
},
components: { A, B }
}
</script>
Here is a solution for a little more complicated and realistic use case. In this use case you have to render multiple different components using v-for.
The parent component passes an array of components to create-components. create-components will use v-for on this array, and display all those components with the correct event.
I'm using a custom directive custom-events to achieve this behavior.
parent:
<template>
<div class="parent">
<create-components :components="components"></create-components>
</div>
</template>
<script>
import CreateComponents from '#/components/CreateComponents'
import ComponentA from '#/components/ComponentA'
import ComponentB from '#/components/ComponentB'
export default {
name: 'parent',
data() {
return {
components: [
{
is: ComponentA,
events: {
"change":this.componentA_onChange.bind(this)
}
},
{
is: ComponentB,
events: {
"click":this.componentB_onClick.bind(this)
}
}
]
}
},
methods: {
componentA_onChange() {
alert('componentA_onChange');
},
componentB_onClick() {
alert('componentB_onClick');
}
},
components: { CreateComponents }
};
</script>
create-components:
<template>
<div class="create-components">
<div v-for="(component, componentIndex) in components">
<component v-bind:is="component.is" v-custom-events="component.events"></component>
</div>
</div>
</template>
<script>
export default {
name: 'create-components',
props: {
components: {
type: Array
}
},
directives: {
CustomEvents: {
bind: function (el, binding, vnode) {
let allEvents = binding.value;
if(typeof allEvents !== "undefined"){
let allEventsName = Object.keys(binding.value);
allEventsName.forEach(function(event) {
vnode.componentInstance.$on(event, (eventData) => {
allEvents[event](eventData);
});
});
}
},
unbind: function (el, binding, vnode) {
vnode.componentInstance.$off();
}
}
}
}
</script>
You don't have to dynamically add them.
<component v-bind:is="currentView" #click="onClick" #change="onChange">
If you want to be careful you can bail in the handler of the currentView is not correct.
methods: {
onClick(){
if (this.currentView != A) return
// handle click
},
onChange(){
if (this.currentView != B) return
// handle change
}
}

Mount parent component in child

I have two files named Recursive.vue and Value.vue.
In the first instance Recursive is the parent. Mounting Recursive in Recursive goes great, same for mounting Value in Recursive and after that Value in Value.
But when I've mounted Value in Recursive and trying to mount Recursive in Value after that I get the following error:
[Vue warn]: Failed to mount component: template or render function not defined.
(found in component <recursive>)
How can I make my problem work?
This is what my files are looking like:
Recursive
<template>
<div class="recursive">
<h1 #click="toggle">{{comps}}</h1>
<div v-if="isEven">
Hello
<value :comps="comps"></value>
</div>
</div>
</template>
<script>
import Value from './Value.vue'
export default {
name: 'recursive',
components: {
Value
},
props: {
comps: Number
},
computed: {
isEven () {
return this.comps % 2 == 0;
}
},
methods: {
toggle () {
this.comps++;
}
}
}
</script>
Value
<template>
<div class="value">
<h1 #click="toggle">{{comps}}</h1>
<div v-if="isEven">
<recursive :comps="comps"></recursive>
</div>
</div>
</template>
<script>
import Recursive from './Recursive.vue'
export default {
name: 'value',
components: {
Recursive
},
props: {
comps: Number
},
computed: {
isEven () {
return this.comps % 2 == 0;
}
},
methods: {
toggle () {
this.comps++;
}
}
}
</script>
Mounter
<template>
<div class="mounter">
<h1>HI</h1>
<recursive :comps="comps"></recursive>
</div>
</template>
<script>
import Recursive from './Recursive'
export default {
name: 'mounter',
components: {
Recursive
},
data () {
return {
comps: 0
}
}
}
</script>
I had a similar problem before. The only way out was declaring the component as "global", because importing it in the component which actually required it never worked.
new Vue({
...
})
Vue.component('recursive', require('./Recursive'))
Then you can just use without importing:
// Mounted
<template>
<div class="mounter">
<h1>HI</h1>
<recursive :comps="comps"></recursive>
</div>
</template>
<script>
export default {
name: 'mounter',
data () {
return {
comps: 0
}
}
}
</script>

Categories