D
D
Dauren S2020-11-01 10:53:03
Vue.js
Dauren S, 2020-11-01 10:53:03

Can Vue set a cookie on watch?

I want the page to return to the login page itself, if the cookie has expired or the user has deleted the cookies manually, is it possible to hang a watch on the cookie? Or how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-11-11
@Aetae

First: watch- this is an internal feature of Vue, and it only works on reactive properties.
Secondly, there are no events for cookie changes, but you can always just watch the changes by interval yourself, something like this:

const cookies = Vue.observable({});

(function update(prevString) {
  const cookieString = document.cookie;

  if (prevString !== cookieString) {
    const cookieObject = Object.fromEntries(
      cookieString.split(/; */)
        .map(
          c => c
            .split('=', 2)
            .map(decodeURIComponent)
        )
    );

    for (const [name, value] of Object.entries(cookies)) {
      if (name in cookieObject) {
        if (cookieObject[name] === value)
          delete cookieObject[name];
      } else {
        Vue.delete(cookies, name);
      }
    }

    for (const [name, value] of Object.entries(cookieObject)) {
      Vue.set(cookies, name, value);
    }
  }

  setTimeout(update, 100, cookieString);
}());

Vue.util.defineReactive(Vue.prototype, '$cookies', cookies);
Now you can do this (if you need support for setting new values ​​​​through - it's on your own) this.$watch('$cookies.cookie_name', () => {...})
this.$cookies.cookie_name = 'cookie_value'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question