Vuejs3 : How can i render "transition" in rouer.js of vue-router-next? - vue-router

I tried to do it like this ,but the "transition" tag is useless.
{
path: 'PATH',
name: 'NAME',
component: {
render() {
return h('div', [h(resolveComponent('router-view'), {
default: (props) => h(resolveComponent('transition'), {
name: "fade-transform-vertical",
mode: "out-in"
}, {default: () => h(props.Component)})
})]);
}
},
meta: {title: 'A', icon: 'el-icon-discount'},
children: [...]
}
Finally, I can only create a new Vue file containing
<template>
<div>
<router-view v-slot="{ Component }">
<transition name="fade-transform-vertical" mode="out-in">
<keep-alive>
<component :is="Component"/>
</keep-alive>
</transition>
</router-view>
</div>
</template>
I dont want to create a new file,Is there a better solution?

Related

Vue component prop not updating on $emit

I need to update the component's prop on every route change but it stays with the last info given.
For example, I fill the form in RouteTwo, with id, name, lastname and phone, and if I change to RouteOne, ComponentOne stays with those four values (including phone) until I start filling the form in RouteOne.
I'm working with vue 2.6.12, vue-router 3.4.9
Here's an example code:
General.vue
<template>
<div>
<div>
<router-view #data-updated="updateFunction"></router-view>
</div>
<div>
<component-one v-bind:component-prop="reactiveProp" />
</div>
</div>
</template>
<script>
import ComponentOne from './ComponentOne.vue';
export default {
components: {
ComponentOne,
},
data: () => ({
reactiveProp
}),
methods: {
updateFunction(value) {
this.reactiveProp = value;
},
}
}
</script>
ComponentOne.vue
<template>
<div>
<p>{{ componentProp.id }}</p>
<p>{{ componentProp.name }}</p>
<p>{{ componentProp.lastname }}</p>
<p v-if="routePath == 'routetwo'">{{ componentProp.phone }}</p>
</div>
</template>
<script>
export default {
props: {
componentProp: Object,
},
data: () => ({
routePath: ''
}),
mounted() {
this.routePath = this.$route.path.split('/').at(-1);
},
}
</script>
RouteOne.vue
<template>
<div>
<input type="text" v-model="dataObject.id" />
<input type="text" v-model="dataObject.name" />
<input type="text" v-model="dataObject.lastname" />
</div>
</template>
<script>
export default {
data: () => ({
dataObject: {
id: '',
name: '',
lastname: '',
},
}),
methods: {
// some logic methods
},
watch: {
dataObject: {
handler: function() {
this.$emit('data-updated',this.dataObject);
},
deep: true,
}
},
}
</scipt>
RouteTwo.vue
<template>
<div>
<input type="text" v-model="dataObject.id" />
<input type="text" v-model="dataObject.name" />
<input type="text" v-model="dataObject.lastname" />
<input type="text" v-model="dataObject.phone" />
</div>
</template>
<script>
export default {
data: () => ({
dataObject: {
id: '',
name: '',
lastname: '',
phone: '',
},
}),
methods: {
// some logic methods
},
watch: {
dataObject: {
handler: function() {
this.$emit('data-updated',this.dataObject);
},
deep: true,
}
},
}
</scipt>
Router
{
name: 'general',
path: '/general',
component: () => import('General.vue'),
children: [
{
name: 'route-one',
path: 'routeone',
component: () => import('RouteOne.vue')
},
{
name: 'route-two',
path: 'routetwo',
component: () => import('RouteTwo.vue')
}
]
}
Switching routes doesn't cause a change in dataObject, so no emit will fire. Technically, switching routes causes one route component to be unmounted (destroyed), and the next route component to be created, meaning dataObject is created/recreated every time you switch back and forth, which is fundamentally different from dataObject being "changed" (which activates the watcher).
Instead, put a watcher on the route itself in the General component and reset reactiveProp when that watcher activates. This will clear the fields when going between RouteOne and RouteTwo:
watch: {
$route(to, from) {
this.reactiveProp = {};
},
},

Pass component as prop in Vue JS

Intro: I am exploring Vue Js and got stuck while trying to make a dynamic data table component the problem I am facing is that I cannot pass a component via props and render it inside a table.
Problem: So basically what I am trying to do is to pass some custom component from headers prop in v-data-table such as:
headers = [
{ text: 'Name', value: 'name' },
{
text: 'Phone Number',
value: 'phone_number',
render: () => (
<div>
<p>Custom Render</p>
</div>
)
},
{ text: 'Actions', value: 'actions' }
]
So from the code above we can see that I want to render that paragraph from the render function inside Phone Number header, I did this thing in React Js before, but I cannot find a way to do it in Vue Js if someone can point me in the right direction would be fantastic. Thank you in advance.
You have 2 options - slots and dynamic components.
Let's first explore slots:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="{item}">
<v-chip>{{ item.phone_number }}</v-chip>
</template>
<template slot="item.company_name" slot-scope="{item}">
<v-chip color="pink darken-4" text-color="white">{{ item.company_name }}</v-chip>
</template>
</v-data-table>
</template>
The data table provides you slots where you can customize the content. If you want to make your component more reusable and want to populate these slots from your parent component - then you need to re-expose these slots to the parent component:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="props">
<slot name="phone" :props="props" />
</template>
<template slot="item.company_name" slot-scope="props">
<slot name="company" :props="props" />
</template>
</v-data-table>
</template>
If you don't know which slots will be customized - you can re-expose all of the data-table slots:
<template>
<v-data-table
:headers="headers"
:items="items"
:search="search"
hide-default-footer
:options.sync="pagination"
:expanded="expanded"
class="tbl_manage_students"
height="100%"
fixed-header
v-bind="$attrs"
#update:expanded="$emit('update:expanded', $event)"
>
<!-- https://devinduct.com/blogpost/59/vue-tricks-passing-slots-to-child-components -->
<template v-for="(index, name) in $slots" v-slot:[name]>
<slot :name="name" />
</template>
<template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
<slot :name="name" v-bind="data" />
</template>
<v-alert slot="no-results" color="error" icon="warning">
{{ $t("no_results", {term: search}) }}"
</v-alert>
<template #footer="data">
<!-- you can safely skip the "footer" slot override here - so it will be passed through to the parent component -->
<table-footer :info="data" #size="pagination.itemsPerPage = $event" #page="pagination.page = $event" />
</template>
</v-data-table>
</template>
<script>
import tableFooter from '#/components/ui/TableFooter'; // you can safely ignore this component in your own implementation
export default
{
name: 'TeacherTable',
components:
{
tableFooter,
},
props:
{
search:
{
type: String,
default: ''
},
items:
{
type: Array,
default: () => []
},
sort:
{
type: String,
default: ''
},
headers:
{
type: Array,
required: true
},
expanded:
{
type: Array,
default: () => []
}
},
data()
{
return {
pagination:
{
sortDesc: [false],
sortBy: [this.sort],
itemsPerPageOptions: [25, 50, 100],
itemsPerPage: 25,
page: 1,
},
};
},
watch:
{
items()
{
this.pagination.page = 1;
},
sort()
{
this.pagination.sortBy = [this.sort];
this.pagination.sortDesc = [false];
},
}
};
</script>
Dynamic components can be provided by props:
<template>
<v-data-table :items="dataItems" :headers="headerItems">
<template slot="item.phone_number" slot-scope="{item}">
<component :is="compPhone" :phone="item.phone_number" />
</template>
<template slot="item.company_name" slot-scope="{item}">
<component :is="compCompany" :company="item.company_name" />
</template>
</v-data-table>
</template>
<script>
export default
{
name: 'MyTable',
props:
{
compPhone:
{
type: [Object, String], // keep in mind that String type allows you to specify only the HTML tag - but not its contents
default: 'span'
},
compCompany:
{
type: [Object, String],
default: 'span'
},
}
}
</script>
Slots are more powerful than dynamic components as they (slots) use the Dependency Inversion principle. You can read more in the Markus Oberlehner's blog
Okay, I don't believe this is the best way possible but it works for me and maybe it will work for someone else.
What I did was I modified the headers array like this:
headers = [
{ text: 'Name', align: 'start', sortable: false, value: 'name' },
{
text: 'Phone Number',
key: 'phone_number',
value: 'custom_render',
render: Vue.component('phone_number', {
props: ['item'],
template: '<v-chip>{{item}}</v-chip>'
})
},
{ text: 'Bookings', value: 'bookings_count' },
{
text: 'Company',
key: 'company.name',
value: 'custom_render',
render: Vue.component('company_name', {
props: ['item'],
template:
'<v-chip color="pink darken-4" text-color="white">{{item}}</v-chip>'
})
},
{ text: 'Actions', value: 'actions', sortable: false }
]
And inside v-data-table I reference the slot of custom_render and render that component there like this:
<template v-slot:[`item.custom_render`]="{ item, header }">
<component
:is="header.render"
:item="getValue(item, header.key)"
></component>
</template>
To go inside the nested object like company.name I made a function which I called getValue that accepts 2 parametes, the object and the path to that value we need which is stored in headers array as key (ex. company.name) and used loadash to return the value.
getValue function:
getValue (item: any, path: string): any {
return loadash.get(item, path)
}
Note: This is just the initial idea, which worked for me. If someone has better ideas please engage with this post. Take a look at the props that I am passing to those dynamic components, note that you can pass more variables in that way.

How can I make keep-alive working in vue?

There are form, table and pagination in the page list. I want to keep the form input, table data and current page number unchanged after back from detail.vue, but it always refreshes every time.
Do I need to store the form data, table data and page number in somewhere so as to make it works? Thanks.
router
{
path: '/list',
name: 'List',
component: resolve => require(['#/pages/list'], resolve),
meta: {
keepAlive: true
}
}
App.vue
<div class="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
list.vue
pagination is inside component ListTable
<template>
<div class="app-container">
<el-form ref="form" :model="form" label-width="100px">
<el-form-item label="MID" prop="name">
<el-input v-model="form.mid" />
</el-form-item>
<el-form-item label="Name" prop="name">
<el-input v-model="form.name" />
</el-form-item>
<el-form-item label="Birthdate" prop="birthdate">
<el-date-picker
v-model="form.birthdate"
value-format="yyyy-MM-dd"
/>
</el-form-item>
</el-form>
<ListTable ref="childTable" :listdata="listData" :currpage="currPage" />
</div>
</template>
<script>
export default {
name: 'MemberList',
components: {
ListTable: () => import('#/components/Membership/ListTable')
},
data() {
return {
currPage: 1,
listData: [],
form: {
mid: '',
name: '',
birthdate: '',
}
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
// get list data
this.listData = ***
.....
},
}
</script>
First you need set key for your component to keep-alive makes difference between rendered components
<keep-alive>
<router-view v-if="$route.meta.keepAlive" :key="$route.fullPath"></router-view>
</keep-alive>
Second you should put ListTable to another keep-alive to inform vue you want store rendered component too
<keep-alive>
<ListTable ref="childTable" :listdata="listData" :currpage="currPage" :key="currPage"/>
</keep-alive>

Separate navigation drawers for certain routes in vue-router

I'm building a Vuetify app in combination with Vuex and vue-router. Some of the views uses the default navigation drawer, but others has different items in their navigation drawers. This documentation say I can pass props to view components. So I implement it like this:
routes/index.js
{
path: '/courses/:courseId/lessons/:lessonId',
name: 'Course 1',
components: {
default: () => import('#/views/ViewLesson.vue'),
sidebar: () => import('#/components/CourseNavBar/CourseNavBar.vue')
},
props: {
items: [
{ text: "Link 1", href:"/link1" },
{ text: "Link 2", href:"/link2" }
]
}
}
src/App.vue
<template>
<v-app>
<v-app-bar
app
color="primary"
dark
>
<h1>My Project</h1>
</v-app-bar>
<v-navigation-drawer><router-view :items="items" name="sidebar"/></v-navigation-drawer>
<v-content>
<router-view />
</v-content>
</v-app>
</template>
But apparently,
src/components/CourseNavBar.vue
<template>
<!-- <v-navigation-drawer :value="1"> -->
<v-list dense>
<navbar-item v-for="(item, i) in items" :key="i" :item="item" >
{{ item.text }}
</navbar-item>
</v-list>
<!-- </v-navigation-drawer> -->
</template>
<script>
import NavBarItem from './NavBarItem.vue'
export default {
props: {
items: Array
},
components: {
'navbar-item': NavBarItem
}
}
</script>
But <CourseNavBar>'s props is still undefined. What am I doing wrong here?
There are a few issues...
Replace = with :...
items: [
{ text:"Link 1", href:"/link1" },
{ text:"Link 2", href:"/link2" }
]
And the sidebar component (not router-view) should be in the slot for the navigation-drawer...
<v-navigation-drawer><sidebar :items="items"></sidebar></v-navigation-drawer>
Demo: https://codeply.com/p/oNInfpTwvK
In your
routes\index.js
you need to define the props option for each of the named views:
{
path: '/courses/:courseId/lessons/:lessonId',
name: 'Course 1',
components: {
default: () => import('#/views/ViewLesson.vue'),
sidebar: () => import('#/components/CourseNavBar/CourseNavBar.vue')
},
props: {
default: true,
sidebar: true,
items: [
{ text: "Link 1", href: "/link1" },
{ text: "Link 2", href: "/link2" }
]
}
}
And following on from what #Zim said, you've used "=" instead of ":" when assigning the href value to the props items array.
You can use <router-view name="sidebar"/> to output the named component.

How to defined a array list in props and data

In my project, I use vue.js.
I want to display content of list with nested loop。 In parent page, i have defined:
<template>
<div>
<detail-header></detail-header>
......
<detail-list></detail-list>
</div>
</template>
The component of detail-list is :
<template>
<div>
<div v-for="(item, index) of list" :key="index">
<div class="item-title border-bottom">
<span class="item-title-icon"></span>
{{item.title}}
</div>
<div v-if="item.children" class="item-children">
<detail-list :list="item.children"></detail-list>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'DetailList',
props: {
list: Array
},
data () {
return {
list: [{
title: 'adult',
children: [{title: 'threePeople',children: [{ title: 'threePeople-w'}]}, {title: 'fivePeople'}]
}, {
title: 'student'
}, {
title: 'child'
}, {
title: 'offer'
}]
}
}
}
</script>
unlucky, I got a error message:
Duplicated key 'list' of list: [{ in detail-list
who can help me ?
If you want this to work, keep the list in props (and remove it from DetailList's data) and define in your parent page's data.
So the first DetailList and its children will have the list as a prop.
So you'll have in the parent page :
<template>
<div>
<detail-header></detail-header>
......
<detail-list :list="list"></detail-list>
</div>
</template>
<script>
export default {
name: 'Parent',
data () {
return {
list: [{ ... the list ... }]
}
}