HelloWorld.vue
<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
<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
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.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:- https://codesandbox.io/s/vibrant-dhawan-3id77?file=/src/main.js
If you please go through my code once above, initially I have some router-link and onclick of router-link, I am able to redirect to User.vue component. Where some details will pre populated and those details i can able to edit and click on submit button, to update the array.
After successfully updating the array, Here comes the issue like, If i simply click on refresh button. Even the updated array also getting reset and set to the default value
I am not sure, How to keep the updated array (keep the same value) Even if page is refreshed also. Do I need to use any vuex or manage the updated array value in localstorage or How is the real-time scenario takes place?
CodePudding user response:
On each refresh your app is re-rendered and in HelloWorld.vue
you get your data from local file, that's why you get the same array every time.
To render your updated array after refresh you will need to store the data in localStorage
or in sessionStorage
and if data exists there get that, if not use the data from local file.
State is not remembered on refresh that's why you need to store it somewhere.
If you're planning to use vuex
you can save data after refresh with vuex-persistedstate
. More info: Vuex state on page refresh