HelloWorld.vue
Dynamic routing in Vuejs:
<template>
<div>
<b>Vuejs dynamic routing</b>
<div v-for="item in items" :key="item.id">
<b>{{ item.id }}.</b>
<router-link :to="{ name: 'UserWithID', params: { id: item.id, item } }">
{{ item.val }}{{ item.kk }}
</router-link>
</div>
<br /><br /><br />
</div>
</template>
<script>
import { data } from "../data";
export default {
name: "HelloWorld",
data() {
return {
items: data,
};
},
};
</script>
User.vue
Edit user details form:
<template>
<div>
<form>
<label>Val:</label><br />
<input type="text" id="val" name="val" v-model="val" /><br />
<label>kk:</label><br />
<input type="text" id="kk" name="kk" v-model="kk" /><br /><br />
<button @click="updateData">submit</button>
</form>
</div>
</template>
<script>
import { data } from "../data";
export default {
name: "User",
props: {
item: {
required: true,
type: Object,
},
},
data: function () {
return {
val: this.item.val,
kk: this.item.kk,
};
},
methods: {
updateData() {
const id = this.$route.params.id;
let newData = data.find((value) => value.id === id);
newData.kk = this.kk;
newData.val = this.val;
this.$router.push({ path: "/" });
},
},
};
</script>
main.js
Vue Router setup:
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import User from "./components/User.vue";
// Vue Router Configuration
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{ path: "/", name: "User", component: HelloWorld, props:true },
{ path: "/User/:id", name: "UserWithID", component: User, props:true }
]
});
Vue.config.productionTip = false;
new Vue({
router,
render: (h) => h(App)
}).$mount("#app");
This is my complete working code with dynamic routing and user details editing functionality. If you encounter issues with page refresh resetting updated array values, consider using Vuex or local storage to persist the changes even after a refresh.