Home > Enterprise >  How to update the details dynamically in vuejs?
How to update the details dynamically in vuejs?

Time:12-21

User.vue

<template>
  <div>
    <form>
      <label>Val:</label><br />
      <input type="text" id="val" name="val" v-model="item.val" /><br />
      <label>kk:</label><br />
      <input type="text" id="kk" name="kk" v-model="item.kk" /><br /><br />
      <input type="submit" value="Submit" @click="updatedata" />
    </form>
  </div>
</template>

<script>
export default {
  name: "User",
  data: function () {
    return {
      val: "",
      kk: "",
    };
  },
  methods: {
    updatedata() {
      val: this.item.val,
      kk: this.item.kk,
    },
  },
};
</script>

Helloworld.vue

<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>
    </div>
    <br /><br /><br />

    {{ $route.params.id }}
  </div>
</template>

<script>
import User from "./User.vue";
export default {
  name: "HelloWorld",
  components: {},
  data() {
    return {
      items: [
        { id: 1, val: "1", kk: "mm" },
        { id: 2, val: "22", kk: "aa" },
        { id: 3, val: "55", kk: "dd" },
        { id: 4, val: "77", kk: "gg" },
      ],
    };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

I am trying to update data in vuejs, I have given routing and able to make it dynamic. But when trying to update the data. How to give reference to the component and update the data. i have taken click event where onclick of that button. I should able to update the data.

Code link:- https://codesandbox.io/s/agitated-forest-wl76w?file=/src/components/User.vue

reference code:- https://codepen.io/Godex/pen/yPYeJe

CodePudding user response:

Each of your components is a separate Vue instance. That means you can't access the same items object using this.items in the User or HelloWorld components.

What you need to do is "raise up the state" so that both components can access the same items object. You can either do this using a mutual parent component and props or by using a store like vuex. Documentation for props: https://vuejs.org/v2/guide/components-props.html Documentation for vuex: https://vuex.vuejs.org/

I've modified your codesandbox using props: https://codesandbox.io/s/priceless-gauss-62tqm


In a couple of words:

  • Display the values (items) passed from the parent component (or vuex) and use it as the "source of truth".
  • Emit/dispatch an event (e.g. update) passing the new data to the component.
  • Update the data in the parent component/store.
  • Related