I have a component which gathers data from an API. The data brought back from the API is an array with details in. One of the values in the array is the type of component which should be rendered, all other data is passed through to the component.
I'm trying to render the correct component based of the value brought back from the database, but it is sadly not working.
I'm new to Vue but had it working in vue2 but would like it to work in Vue 3 using the composition API.
this is my component code which I want to replace:
<component :is="question.type" :propdata="question" />
When viewed within the browser this is what is actually displayed, but doesn't use the SelectInput component:
<selectinput :propdata="question"></selectinput>
SelectInput is a component with my directory, and works as intended if I hard code the :is value, like below:
<component :is="SelectInput" propdata="question" />
my full component which calls the component component and swaps components:
<template>
<div class="item-group section-wrap">
<div v-bind:key="question.guid" class='component-wrap'>
<div class="component-container">
<!-- working -->
<component :is="SelectInput" :propData="question" />
<!-- not working -->
<component v-bind:is="question.type" :propData="question" />
</div>
</div>
</div>
</template>
<script setup>
import { defineProps, toRefs } from 'vue';
import SelectInput from "./SelectInput";
import TextareaInput from "./TextareaInput";
const props = defineProps({
question: Object,
});
const { question } = toRefs(props);
</script>
In case that your Components filenames are equal to the type specifier on your question Object, then you could dynamically import them to save some code lines.
This would also result in better scalability since you don't have to touch this component anymore in case you create more types.
<template>
<div class="item-group section-wrap">
<div v-bind:key="question.guid" class='component-wrap'>
<div class="component-container">
<!-- working -->
<component v-bind:is="getComponent(question.type)" :propData="question" />
</div>
</div>
</div>
</template>
<script setup>
import { defineProps, toRefs } from 'vue';
const props = defineProps({
question: Object,
});
// GIVEN THE question.types are equal to the fileNames of the components to render:
const getComponent = (name) => import(`./${name}.vue`);
const { question } = toRefs(props);
</script>
Figured out that because I'm using script setup the components aren't named so the component component doesn't know which component to render.
so, i created an object with the components and a reference to the component:
const components = {
'SelectInput': SelectInput,
'TextareaInput': TextareaInput
};
and another function which takes in the component i want to show and links it to the actual component:
const component_type = (type) => components[type];
then in the template i call the function and the correct component is rendered:
<component v-bind:is="component_type(question.type)" :propData="question" />
complete fixed code:
<template>
<div class="item-group section-wrap">
<div v-bind:key="question.guid" class='component-wrap'>
<div class="component-container">
<!-- working -->
<component v-bind:is="component_type(question.type)" :propData="question" />
</div>
</div>
</div>
</template>
<script setup>
import { defineProps, toRefs } from 'vue';
import SelectInput from "./SelectInput";
import TextareaInput from "./TextareaInput";
const props = defineProps({
question: Object,
});
const components = {
'SelectInput': SelectInput,
'TextareaInput': TextareaInput
};
const component_type = (type) => components[type];
const { question } = toRefs(props);
</script>
Not too sure if this is the correct way of doing this but it now renders the correct component.
Related
When I have a child component like this:
<script setup>
import { defineExpose } from 'vue'
const validate = () => {
console.log('validate')
}
defineExpose({ validate })
</script>
<template>
hello
</template>
and parent component in which I use child:
<script setup>
import { ref } from 'vue'
const test = ref()
const validate = () => {
console.log('test', test.value)
}
</script>
<template>
<div ref="test">
<Child />
</div>
<button #click="validate">
click me
</button>
</template>
Is it possible to access validate method from the child component via template ref which is on the wrapper div in parent component?
EDIT:
I update my playground link in which I completed the task but I'm using parent instance instead of provide/inject:
https://sfc.vuejs.org/#eNqNU9FuozAQ/BWfXyBSYt4jqK463Un9hqOqKCypW7At29BWEf/eXcAkJVXaSEHszu4wnl0f+a0xou+A73nqSiuNZw58Z25yJVujrWdHZqFmA6utblmEpdEC/dO2nfMioYCYTvCdMp1f8DGaC0qtHCLUnhF9vMkVYyHvAR8Zizcsu2FHQqhS9EXTAT1lVXigliFXaTKpRr0YeGhNgyBFPh3lIXuWcyLIOaYZ/tJJWPKDMB2PNb6Gf/rYea8V+102snxBbpK7cI9J1sLUPJUilCaLNL7lkz+7tjDi2WmF3o+nzGfA5Xw/nZty6BjFOX/y3rh9kri6JBufndD2kOCbsJ3ysgUBrt09Wv3qwCJxzrdnHAkme7A7C6oCC/Ya56r0gpdo0fsBjxKmfm1/Kqilgr9vRjtYLVIY+TxVqdWttcU7Tv///QqDi5VgcQPnrUzXa6JN8PGUn3aN5NPnz7XFx+Vb2wtFA7ZdW7ZK9mGBXKNP+zPlP89/uQrXXDNW97JCJQfwfzqLw/B3aEehym9MXBlFmG5ANPoQR0uJJAm/oukSBQIZ+LMvPjr6hvpqFoc6YQqqEP7dgHh4UEWLrVnGItqKaPZ+XQyj11W4yMFgYTr3FAd931/un/s9fAD8ILMq
How to actually get rid of parent instance and use provide inject to achieve same result as in the playground from link above?
The ref needs to be on the actual Child element, not the parent div. The method is a property of test.value, so if the method is called "validate" you can run it with test.value.validate().
You also need to make sure the Child component is imported
Try this SFC Playground instead. The "click me" button will console.log the word "validate" which comes from the Child component.
<script setup>
import Child from './Child.vue'
import { ref } from 'vue'
const test = ref()
const childFunc = () => {
test.value.validate()
}
</script>
<template>
<div>
<Child ref="test" />
</div>
<button #click="childFunc">
click me
</button>
</template>
I have this simple file:
<script setup>
import { ref } from 'vue'
import TheHeader from '#/components/_headerbar/TheHeader.vue'
import TheSidebar from '#/components/_sidebar/TheSidebar.vue'
const sidebarState = ref(false)
const onSidebarToggle = () => {
sidebarState.value = !sidebarState.value
}
</script>
<template>
<QLayout view="hHh lpR fFf">
<TheHeader #toggle-sidebar="onSidebarToggle" />
<TheSidebar :sidebar-state="sidebarState.value" />
<QPageContainer>
<RouterView v-slot="{ Component }">
<component :is="Component" />
</RouterView>
</QPageContainer>
</QLayout>
</template>
The sidebarState variable here updates just fine everytime the event toggle-sidebar is fired, but the prop that recieve its value never updates and I just don't know what is happening.
This is the TheSidebar.vue file:
<script setup>
const props = defineProps({
sidebarState: {
type: Boolean,
default: true
}
})
</script>
<template>
<QDrawer
:model-value="props.sidebarState"
show-if-above
side="left"
bordered
>
content
</QDrawer>
</template>
Debugging here I can tell the sidebarState prop from TheSidebar.vue file just never changes, even though the data prop of TheHeader.vue sidebarState changes just normally.
What am I doing wrong?
You shouldn't use .value in template with refs of top-level properties. The value is automatically unwrapped for you (note: make sure the toggle in the top left of the docs is switched from "Options" to "Composition" for link to correctly work).
Simply remove .value and your code should work
<TheSidebar :sidebar-state="sidebarState" />
I have a basic SPA with two child components, a header and a side menu (left drawer).
I wish the user to be able to click a button on the header component to call a function in the side menu component.
I understand I can use props to access a variable between parent & child components however how can I update a value between two sibling components?
Header
<q-btn dense flat round icon="menu" #click="toggleLeftDrawer" />
Left Drawer
import { ref } from 'vue'
export default {
setup () {
const leftDrawerOpen = ref(false)
return {
leftDrawerOpen,
toggleLeftDrawer () {
leftDrawerOpen.value = !leftDrawerOpen.value
}
}
}
}
Use global stores. Create a file
/store.js (you can obviously use any name)
Inside this file store/write the following code:-
import { reactivity } from 'vue'
export const global = reactive({
yourVariable: 'initialValue'
})
You can then import this variable and interact with it from anywhere and the change will be global. See the code below:
In header component:-
<script setup>
import { global } from './store.js'
const clicked = ()=> {
global.yourVariable = 'changed'
}
</script>
<template>
<button #click="clicked">
</button>
</template>
In leftDrawer Component:-
<script setup>
import { global } from './store.js'
</script>
<template>
<div>
{{ global.yourVariable }}
<!--You'll see the change:)-->
</div>
</template>
Then add these two in your main vue:-
<script setup>
import headerComponent from '...'
import leftDrawerComponent from '....'
//....
</script>
<template>
<div>
<header-component />
<left-drawer-component />
</div>
</template>
<template>
<p>
<input type="text" v-model="appInput">
{{ appInput }}
</p>
<ParentComponent :appInput='appInput' :appObject='appObject'/>
</template>
<script setup>
import ParentComponent from './components/ParentComponent.vue'
import { ref } from 'vue'
const appInput = ref('')
const appObject = ref({
text1: 'text1',
text2: 'text2'
})
</script>
<!-- ------------------------------------- -->
<template>
<!-- {{ appInput }} -->
{{ props.appInput }}
<!-- {{ appObject }} -->
{{ props.appObject.text1 }}
<ChildComponentVue :appInput='appInput'/>
</template>
<script setup>
import { defineProps } from 'vue';
import ChildComponentVue from './ChildComponent.vue';
const props = defineProps(['appInput', 'appObject'])
// const appInput = props.appInput
// const appObject = props.appObject
</script>
Using Vue 3, I want to reactively render text from App.vue on ParentComponent.vue and ChildComponent.vue by passing data from App to Parent, and Parent to child successively.
But when I reassign props data on ParentComponent for use it conveniently, it lose reactivity.
I tried repack it with ref() on ParentComponent, but as Vue3 Official Document says, it doesn't work.
But it is too dirty to use passed data without reassign in template (like {{ props.appObject.text1 }}) and too hard to repass not entire but just some part of passed data.
and here are my questions
Are there some ways to use and repass passed data more concisely without losing its reactivity?
What is the convension on Vue3 to deal with this kind of problem happen. Just using Vuex?
The documentation is not enough to be able to do the emit. I have seen many tutorials and nothing works, now I am testing this
Child component
<div #click="$emit('sendjob', Job )"></div>
With the Vue DevTools plugin I can see that the data is sent in the PayLoad, but I can't find a way to receive this emit from the other component.
Many people do this
Any other component
<template>
<div #sendjob="doSomething"></div>
</template>
<script>
export default {
methods:{
doSomething(){
console.log('It works')
}
}
}
</script>
In my case it doesn't work
You should import the child component in the parent component and use it instead of the regular div tag.
I'm sharing examples for your reference to achieve emits in Vue 3 using <script setup> and Composition API. I strongly suggest going with <script setup if you are going to use Composition API in Single File Component. However, the choice is yours.
Example with <script setup>: https://v3.vuejs.org/api/sfc-script-setup.html
<!-- App.vue -->
<template>
<UserDetail #user-detail-submitted="userDetailSubmitted"/>
</template>
<script setup>
import UserDetail from './components/UserDetail';
function userDetailSubmitted(name) {
console.log({ name })
}
</script>
<!-- UserDetail.vue -->
<template>
<input type="text" v-model="name" #keyup.enter="$emit('user-detail-submitted', name)" />
</template>
<script setup>
import { ref } from 'vue';
const name = ref('');
</script>
Example using Composition API: https://v3.vuejs.org/api/composition-api.html
<!-- App.vue -->
<template>
<UserDetail #user-detail-submitted="userDetailSubmitted"/>
</template>
<script>
import UserDetail from "./components/UserDetail";
export default {
components: {
UserDetail,
},
setup() {
function userDetailSubmitted(name) {
console.log({ name });
}
return {
userDetailSubmitted
}
},
};
</script>
<!-- UserDetail.vue -->
<template>
<input type="text" v-model="name" #keyup.enter="$emit('user-detail-submitted', name)" />
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const name = ref('');
return {
name,
}
}
}
</script>
You should import this child-component in the parent. And don't rename it to the html's original tag.vue3. You'd better use the Composition API.