Vue3 dynamic render - vue.js

I have a list of components and I want to set a config for them from outside,
For example:
const myConfig = [
{
name: 'example',
renderer: () => (<button #click="clickHanlder">Click me!</button>)
},
...
];
And for my component I want to use myConfig as shown below:
<template>
<div class="example">
<template v-for="(item, index) in myConfig" :key="index">
My Button:
<div class="example-2">{{ item.renderer() }}</div>
</template>
</div>
</template>
Please pay attention that I don't want to use slots
How I can do it?

You could achieve that by using h render function as shown in the following example :
<template v-for="(item, index) in myConfig" :key="index">
My Button:
<div class="example-2">
<component :is="item.renderer" />
</div>
</template>
<script setup lang="ts">
import { h } from 'vue';
const myConfig = [
{
name: 'example',
renderer: h('button', {
onClick:clickHanlder
},'Click me !'),
},
];
function clickHanlder(){
console.log('click btn');
}
</script>

Related

Vue.js Passing a variable in a loop to another component

As a beginner in Vue.js,I am trying to create a Todo app, but problems seems to passing a variable to another component when looping.
i want to pass item to another embedded component.
Here what I have with all the components:
in main.js:
import Vue from "vue";
import App from "./App.vue";
import Todo from "./components/Todo";
import itemComponent from "./components/itemComponent";
Vue.config.productionTip = false;
Vue.component('todo', Todo);
Vue.component('itemcomponent', itemComponent);
new Vue({
render: h => h(App)
}).$mount("#app");
in App.vue:
<template>
<div id="app">
<todo></todo>
<img alt="Vue logo" src="./assets/logo.png" width="25%" />
<!-- <HelloWorld msg="Hello Vue in CodeSandbox!" /> -->
</div>
</template>
<script>
export default {
name: "App",
components: {
},
};
</script>
in Todo.vue:
<template>
<div>
<input type="text" v-model="nameme" />
<button type="click" #click="assignName">Submit</button>
<div v-for="(item, index) in result" :key="item.id">
<itemcomponent {{item}}></itemcomponent>
</div>
</div>
</template>
<script>
import { itemcomponent } from "./itemComponent";
export default {
props:['item'],
data() {
return {
nameme: "",
upernameme: "",
result: [],
components: {
itemcomponent,
},
};
},
methods: {
assignName: function () {
this.upernameme = this.nameme.toUpperCase();
this.result.push(this.nameme);
this.nameme = "";
},
},
};
</script>
in itemComponent.vue:
<template>
<div>
<input type="text" value={{item }}/>
</div>
</template>
<script>
export default {
props: {
item: String,
},
data() {
return {};
},
};
</script>
what is my mistake? thanks for help.
Quite a bunch of mistakes:
You should import single page components inside their parent components and register them there, not in main.js file. EDIT: Explaination to this is given in docs
Global registration often isn’t ideal. For example, if you’re using a build system like Webpack, globally registering all components means that even if you stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download.
You have a component registration in Todo.vue, but you have misplaced it inside data so its is just a data object that is not getting used, move into components.
In your loop you have item.id, but your item is just a plain string, it does not have an id property. Either change item to object with id property, or simply use the index provided in loop (not recommended).
Pass your item as a prop, not mustache template. So in Todo.vue replace {{ item }} with :item="item"
In your ItemComponent.vue you have mustache syntax once again in the attribute. Change value={{item }} to :value="item"
So here's the final code:
main.js
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
in App.vue:
<template>
<div id="app">
<todo></todo>
<img alt="Vue logo" src="./assets/logo.png" width="25%" />
<!-- <HelloWorld msg="Hello Vue in CodeSandbox!" /> -->
</div>
</template>
<script>
import Todo from './components/Todo.vue';
export default {
name: "App",
components: {
Todo,
},
};
</script>
in Todo.vue:
<template>
<div>
<input type="text" v-model="nameme" />
<button type="click" #click="assignName">Submit</button>
<div v-for="(item, index) in result" :key="index">
<itemcomponent :item="item"></itemcomponent>
</div>
</div>
</template>
<script>
import { itemcomponent } from "./itemComponent";
export default {
props:['item'],
data() {
return {
nameme: "",
upernameme: "",
result: [],
};
},
methods: {
assignName: function () {
this.upernameme = this.nameme.toUpperCase();
this.result.push(this.nameme);
this.nameme = "";
},
},
components: {
itemComponent,
}
};
</script>
itemComponent.vue:
<template>
<div>
<input type="text" :value="item"/>
</div>
</template>
<script>
export default {
props: {
item: String,
},
data() {
return {};
},
};
</script>

import dynamically fontawesome icons in Vue

I have a problem rendering icons dynamically. I use v-for to get all the data from the object array. Also, I have a second array where I save the name of the icons I worked with. However, when the first array is looping, the second array (icons) doesn't move.
I tried to create a method that maps the data from the first and second array to create a new array. But nothing happens.
My code:
Component.vue
<template>
<div class="items">
<div class="item" v-for="(param, index) in params" :key="index">
<font-awesome-icon :icon="['fab', 'temp']" :temp="getIcon" :key="index" class="fab fa" />
<h3 class="skills-title">{{ param.name }}.</h3>
<p style="display: none">{{ param.description }}.</p>
</div>
</div>
</template>
<script>
export default {
name: "PxSkillCard",
data() {
return {
params: [],
icons: ["laravel", "wordpress-simple"],
};
},
methods: {
getIcon() {
let temp = this.params.map((aux, index) => {
return [aux, this.icons[index]];
});
},
},
};
</script>
And I separated the fontawesome file in a apart module
fontawesome.js
import Vue from "vue";
import { library } from "#fortawesome/fontawesome-svg-core";
import {
faLaravel,
faWordpressSimple
} from "#fortawesome/free-brands-svg-icons";
import { faPlus } from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/vue-fontawesome";
library.add(
faLaravel,
faWordpressSimple
);
Vue.component("font-awesome-icon", FontAwesomeIcon);
The final result is:
What about with my code (or my logic)?
You are already looping through everything in your template, there's no need to loop again in your function.
Something like this should work.
<template>
<div class="items">
<div class="item" v-for="(param, index) in params" :key="index">
<font-awesome-icon :icon="['fab', icons[index]]" :key="index" class="fab fa" />
<h3 class="skills-title">{{ param.name }}.</h3>
<p style="display: none">{{ param.description }}.</p>
</div>
</div>
</template>
<script>
export default {
name: "PxSkillCard",
data() {
return {
params: [],
icons: ["laravel", "wordpress-simple"],
};
},
};
</script>
This assume, both arrays are the same size and the data in params and icons are in the correct order.

Vuejs 3 props are Proxy

I am passing array as a prop to another component, and when I want to read this on mounted in that component, I got Proxy {}. How to read data from this prop? You can see in example when I want to console log prop, result is Proxy {}. I can see all values in HTML structure, but not in the console on mounted.
<template>
<div class="custom-select-container">
<div class="selected-item" #click="openSelect">
<span class="selected-items-text">{{ selectedItem.name }}</span>
<span class="icon-arrow1_b selected-items-icon" :class="{ active: showOptions }" />
</div>
<transition name="fade">
<ul v-show="options.length && showOptions" class="custom-select-options">
<li v-for="(option, index) in options" :key="index" class="custom-select-item">{{ option.name }}</li>
</ul>
</transition>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
props: {
options: {
type: Array,
default: () => []
}
},
setup(props) {
let showOptions = ref(false);
let selectedItem = ref(props.options[0])
const openSelect = () => {
showOptions.value = !showOptions.value
}
onMounted(() => {
console.log('test', props.options)
})
return {
openSelect,
showOptions,
selectedItem
}
}
}
</script>
Parent component where I am passing data:
<template>
<div class="page-container">
<div>
<div class="items-title">
<h3>List of categories</h3>
<span>({{ allCategories.length }})</span>
</div>
<div class="items-container">
<div class="item" v-for="(category, index) in allCategories" :key="index">
<span class="item-cell size-xs">{{ index + 1 }}.</span>
<span class="item-cell size-l">{{ category.name }}</span>
</div>
</div>
</div>
<custom-select
:options="allCategories"
/>
</div>
</template>
<script>
import CustomSelect from '../components/Input/CustomSelect'
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
components: {
CustomSelect
},
computed: {
},
setup() {
const store = useStore()
const allCategories = computed(() => store.getters['categories/getAllCategories'])
return {
allCategories
}
}
}
</script>
That's how reactivity works in Vue3.
use
console.log(JSON.parse(JSON.stringify(data))
or
console.log(JSON.stringify(data, null, 2))
to show the content of proxies in console

VueJs - pass slot from child component to parent

I am having difficulty to make use of named slot from children in parent component.
So I am making tabs component with main Tabs and child Tab components.
My Tabs:
<template>
<div class="tabsMainContainer">
<div class="tabsContainer">
<ul class="tabsHeader">
<li
v-for="(tab, index) in tabs"
:key="tab.title"
:class="{tabActive: (index == selectedIndex)}"
#click="selectTab(index)"
>
<slot name="icon"/>
{{ tab.title }}
</li>
</ul>
</div>
<div class="tabsContent"><slot/></div>
</div>
</template>
I get tabs object with this.$children
and then my Tab component:
<template>
<div v-show="isActive" class="tab">
<slot name="icon"/>
<slot/>
</div>
</template>
And use of that:
<Tabs class="tabsComponent">
<Tab title="first">
<template v-slot:icon>Icon</template>
Content
</Tab>
<Tab title="second">Content second</Tab>
</Tabs >
while Content as such works fine, it appears in default slot, the icon slot also appears in default slot in main Tab component. How can I get icon slot from children, and display it in icon slot of main Tab component?
I also had a same kind of requirement. What I did was adding slot inside the main component's slot with the same name
In your Tab component
<template>
<div v-show="isActive" class="tab">
<template v-slot:icon>
<slot name="icon" />
</template>
</div>
</template>
First of all, I use google translate. Sorry, I may have spelled it wrong.
https://stackoverflow.com/a/64568036
I got an example from #ingrid-oberbüchler.
My solution
Layout.vue
<Tabs class="tabsComponent">
<Tab title="first">
<template v-slot:icon>Icon</template>
Content
</Tab>
<Tab title="second">Content second</Tab>
</Tabs>
Tabs.vue
<template>
<div class="title">
{{ tabsProvider.tabs[tabsProvider.selectedIndex].props.title }}
</div>
<div class="content">
<slot/>
</div>
<div class="icon">
<component :is="tabsProvider.tabs[tabsProvider.selectedIndex].children.icon"/>
</div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
data() {
return {
tabsProvider: {
selectedIndex: 0,
tabs: [],
count: 0,
},
};
},
provide() {
return {
$tabsProvider: this.tabsProvider,
};
},
created() {
this.tabsProvider.tabs = this.$slots.default().filter((child) => child.type.name === "Tab");
},
}
</script>
Tab.vue
<template>
<div v-show="isActive">
<slot />
</div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
name: "Tab",
props: {
title: {
type: String,
},
},
inject: ["$tabsProvider"],
data() {
return {
index: 0,
isActive: false,
};
},
beforeMount() {
this.index = this.$tabsProvider.count;
this.$tabsProvider.count++;
this.isActive = this.index === this.$tabsProvider.selectedIndex;
},
watch: {
"$tabsProvider.selectedIndex": {
handler(val, oldVal) {
this.isActive = this.index === this.$tabsProvider.selectedIndex;
},
deep: true,
},
},
});
</script>
Simplest example
let's admit x component is parent
<div class="x">x component</div>
let's admit y component is child
<div class="y">y component</div>
How to be process?
<Ycomponent>
<slot name="example1"/>
<slot name="example2"/>
<slot name="example3"/>
</Ycomponent>
<Xcomponent>
<Ycomponent>
<button slot="example1">button</button>
<span slot="example2">Span</span>
<img slot="example3" src="/"/>
</Ycomponent>
</Xcomponent>
I hope I could help.

Vue. Change the contents of one slot from another

I have a component with certain slots.
<v-split-container ref="splitContainer" class="panel-panel">
<template slot="left">
Test
</template>
<template slot="right">
<router-view></router-view> //Show Compontent A
</template>
<template slot="bottom"> //Slot B
Hello
</template>
</v-split-container>
Can I, from component A, change the contents of slot B by calling a function inside the component?
Hi you can do it with Scoped Slot. I have created an example for you how to do it. Please not that I am using v-slots(Some context here) only usable from vue v2.6.
Please take a look at the code example: https://codesandbox.io/s/2030jo20j0?fontsize=14
Child Component
<template>
<div>
<div>
<slot name="msgSlot">{{msg}}</slot>
</div>
<br>
<slot name="bottom" :updateMsg="updateMsg"></slot>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data: () => ({
msg: "Default Message"
}),
methods: {
updateMsg(text) {
this.msg = text;
}
}
};
</script>
Parent Component
<template>
<div id="app">
<HelloWorld>
<template v-slot:msgSlot></template>
<template v-slot:bottom="{updateMsg}">
<input type="text" v-model="msg">
<button #click="updateMsg(msg)">Change Msg</button>
</template>
</HelloWorld>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
data: () => ({
msg: ""
}),
components: {
HelloWorld
}
};
</script>