Javascript 如何在 vuejs 中设置 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50754590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set cookie in vuejs?
提问by Ic3m4n
What is the best practice for setting a cookie in vuejs? I use SSR, so I guess I can't use localStorage.
在 vuejs 中设置 cookie 的最佳实践是什么?我使用SSR,所以我想我不能使用localStorage。
What is the best approach here?
这里最好的方法是什么?
回答by Devansh Saini
You could use the vue-cookieor vue-cookiesnpm package. You can set a cookie in the created method.
您可以使用vue-cookie或vue-cookiesnpm 包。您可以在 created 方法中设置 cookie。
created() {
this.$cookie.set("keyName", keyValue, "expiring time")
}
回答by khan
You can also do it in a plan javascript without using extensions.
您也可以在不使用扩展的情况下在计划 javascript 中执行此操作。
Lets say you want to store Token with expiry of 24 hours inside xios POST response
假设您想在 xios POST 响应中存储 24 小时到期的令牌
axios.post('url', datatosend)
.then(function (response) {
if(response.status == 200){
let d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = "Token=" + response.data.Token + ";" + expires + ";path=/";
}
})
.catch(function (error) {
console.log(error);
});
回答by mpalencia
Use vue-cookies
To use:
使用:
<script src="https://unpkg.com/[email protected]/vue-cookies.js"></script>
<script>
$cookies.set('cookie_name', 'cookie_value');
</script>
回答by Visovan Mihai
I think the easiest and cleanest way is:
我认为最简单和最干净的方法是:
import VueCookies from 'vue-cookies'
VueCookies.set('name' , name, "1h")
This could be added in mutations if you want them in Vuex.
如果您希望在 Vuex 中使用它们,可以将其添加到突变中。
回答by Hira Kumar Maharjan
it would be best to use mountedmethod
最好使用mounted方法
mounted: function() {
document.cookie = "username=John Doe";
}

