解释:
这两个都是存在浏览器中的,在django中sessionStorage存入的值会在浏览器关闭时自动清空,localStorage则是不管是否关闭浏览器,都会保存已经存入的值
使用方法:
存入方法如下:
<template>
<div>
用户名:<input type="text" v-model="username"><br>
密码:<input type="password" v-model="password"><br>
<button @click="logs">登录</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
username:'',
password:''
}
},
methods:{
logs(){
let form_data = new FormData();
form_data.append('username',this.username);
form_data.append('password',this.password);
axios({
url:'http://127.0.0.1:8000/login/',
method:'post',
data:form_data,
}).then(res=>{
console.log(res);
// sessionStorage.setItem('username',this.username)
localStorage.setItem('username',this.username);
localStorage.setItem('userid',res.data.userid);
})
}
}
}
</script>
如何取出存入的值
<template>
<div>
<table border="1">
<tr>
<th>标题</th>
<th>内容</th>
<th>操作</th>
</tr>
<tr v-for="item in datalist">
<td>{{ item.title }}</td>
<td>{{ item.content }}</td>
<td><button @click="pings(item.id)">评论</button></td>
</tr>
</table>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
datalist:[],
}
},
mounted() {
axios({
url:'http://127.0.0.1:8000/shownews/',
method:'get',
}).then(res=>{
console.log(res);
this.datalist = res.data;
})
},
methods:{
pings(id){
// var user = sessionStorage.getItem('username'); # 取值
var user = localStorage.getItem('username');
// console.log(user);
if (!user){
window.location.href = '/login'
}else{
this.$router.push({path:'/comment',query:{id:id}})
}
}
}
}
</script>