Reputation: 587
I have a weird issue with vue-router
.
I have a simple CRUD app for users.
It consists of four different views:
If I go the first time on the edit page of the user with the id 1 everything works like a charm. But if I go back and click on another user and go to the edit page, it will display the form with the values of the user with the id 1 and there is no new ajax request.
It seems that the component will be reused.
I tried to give the form child components different :key
values but no success.
<router-view :key="$route.fullPath"></router-view>
Setting the key on the router-view had no success too...
If I reload the browser it will be displayed correctly
Here a example in a nutshell:
My routes:
import Index from "./views/Index";
import Show from "./views/Show";
import Edit from "./views/Edit";
import Create from "./views/Create";
export default [
{
path: '/admin/users',
name: 'users.index',
component: Index
},
{
path: '/admin/users/create',
name: 'users.create',
component: Create
},
{
path: '/admin/users/:id',
name: 'users.show',
component: Show,
props: true
},
{
path: '/admin/users/:id/edit',
name: 'users.edit',
component: Edit,
props: true
},
];
Edit component (Create is sme without id):
<template>
<ResourceForm
resource="user"
:resource-id="id"
@cancel="$router.push({name: 'users.index'})"
/>
</template>
<script>
import ResourceForm from "../../../components/ResourceForm";
export default {
components: {ResourceForm},
props: ['id'],
}
</script>
ResourceForm component:
<template>
<form @submit.prevent="submitResourceForm">
<component
v-for="(field, index) in fields"
:key="field.name + index"
:ref="`${field.name}-field`"
:is="field.component"
:field="field"
:validation-errors="getValidationErrors(field)"
/>
<div class="mt-8 border-t border-gray-200 pt-5">
<div class="flex justify-end">
<span class="inline-flex rounded-md shadow-sm">
<button type="button" @click="$emit('cancel')"
class="py-2 px-4 border border-gray-300 rounded-md text-sm leading-5 font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800 transition duration-150 ease-in-out">
{{this.cancelText}}
</button>
</span>
<span class="ml-3 inline-flex rounded-md shadow-sm">
<button type="submit"
class="btn">
{{this.submitText}}
</button>
</span>
</div>
</div>
</form>
</template>
<script>
import _ from 'lodash';
import api from "../lib/api";
import Form from "../lib/mixins/Form";
export default {
mixins: [Form],
props: {
resource: {
type: String,
required: true
},
resourceId: {
required: false,
default: null
},
cancelText: {
type: String,
default: 'Cancel'
},
submitText: {
type: String,
default: 'Submit'
},
},
data() {
return {
fields: []
}
},
watch: {
'$route': function () {
console.log('route changed');
this.fetchResourceForm();
}
},
created() {
this.fetchResourceForm();
},
methods: {
async fetchResourceForm() {
let route;
if (this.resourceId !== null) {
route = Cms.route('cms.api.forms.show', {
resource: this.resource,
id: this.resourceId
});
} else {
route = Cms.route('cms.api.forms.new', {resource: this.resource});
}
const response = await api(route);
this.fields = response.data.data.fields;
},
async submitResourceForm() {
const formData = this.getFormData();
try {
const foo = {
...Cms.route('cms.api.forms.store', _.pickBy({
resource: this.resource,
id: this.resourceId
})),
data: formData
};
const response = await api(foo);
this.$emit('success', response.data.data);
} catch (error) {
if (error.response.status === 422) {
this.validationErrors = error.response.data.errors;
Cms.flash('error', 'There are validation errors in the form.')
}
}
}
}
}
</script>
The Cms.route method does generate api routes and has nothing to do with vue-router.
Upvotes: 0
Views: 522
Reputation: 5465
What you need is In Component Guards since these guard methods are available in the components because you passed an imported view directly to vue-router
:
{
path: '/admin/users',
name: 'users.index',
component: Index // <-- makes Component Guards available in './views/Index.vue'
},
Replace:
created() {
this.fetchResourceForm();
}
with:
// Fires if you are already on a DYNAMIC route when a uri parameter like :id changes
// This will for example run if you navigate from `/admin/users/123` to `/admin/users/456`
beforeRouteUpdate(to, from, next) {
this.fetchResourceForm();
next()
},
// Fires if you switch between different router entries.
// When you navigate from `/something` to `/another-path
beforeRouteEnter(to, from, next) {
this.fetchResourceForm();
next()
},
However, if you are fetching data inside a component that is inside a Router View then a watch
will be required as others have suggested but why not just pass the data down as a prop
instead?
Upvotes: 1
Reputation: 1554
Watch the router from any of the parent component.
watch:{
`$route`:function(route){
if(route.name === 'users.create'){
this.fetchData(route.params.id);
}
}
},
methods:{
fetchData:function(id){
// fetch your data corresponding to the id
// save the response to store using `commit`.
// this.$store.commit('SET_FIELDS',response.data.data.fields);
}
}
Then initialise a mutation
and state
in the store
const state = {
fields:{}
}
const mutations = {
SET_FIELDS:(state,value)=>state.fields = value;
}
Inside the ResourceForm
component, you can get the data from store
using computed
method.
computed:{
fields:function(){
return this.$store.state.fields;
}
}
The fields
value will rendered real-time on changing the route.
Upvotes: 2
Reputation: 587
I found the problem. It does not relate to this functionality but to the component which generates the api routes. @Rijosh's solution works if someone encounter this problem in vue-router.
Upvotes: 0
Reputation: 3100
I think you can put the user in a vuex
state and use this state in both component. Or maybe launch the request in beforeEnter
hook
Upvotes: 1