Ryan
Ryan

Reputation: 229

Vue.js - Editing SessionStorage Data

I have a sessionStorage item (cart) which I saved from a form. I also have a button that lets you edit your cart items. What i want to do is whenever the user edits the cart items, the sessionStorage gets updated. How do i do this using vue?

Vue.js Code:

window.onload = function () {

new Vue({
  el: '#cart-items',
  data () {
    return {
      cart: ''
    }
  },
  mounted () {
    if(sessionStorage.cart) {
        const cart1 = sessionStorage.cart;
        this.cart = JSON.parse(cart1);
    }
  },
  computed:{

  },
  methods:{

  }
})

}

Upvotes: 0

Views: 91

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28424

You can set a watch on this variable, and update the sessionStorage every time it changes:

watch: {
    cart: function(val) {
      sessionStorage.setItem("cart", val);
    }
}

If you want a better technique, take a look at Vuex.

Upvotes: 1

Related Questions