Laravel 5 Vue.js如何在单文件组件Vue中使用localstorage

Laravel 5 Vue.js如何在单文件组件Vue中使用localstorage,laravel-5,vuejs2,Laravel 5,Vuejs2,我是Vue.js新手,需要知道如何在登录页面上使用localstorage。在我成功登录到欢迎页面后,如果我手动将URL从“/welcome”更改为“/login”,它将重定向回登录页面,因为我没有使用本地存储。如何使用localstorage解决此问题 代码如下: methods: { login() { if (this.input.username != '' && this.input.password != '') {

我是Vue.js新手,需要知道如何在登录页面上使用localstorage。在我成功登录到欢迎页面后,如果我手动将URL从“/welcome”更改为“/login”,它将重定向回登录页面,因为我没有使用本地存储。如何使用localstorage解决此问题

代码如下:

methods: {
        login() {
            if (this.input.username != '' && this.input.password != '') {

                this.$http.post('http://www.example.com/test', {
                        name: this.input.username,
                        password: this.input.password
                    })
                    .then((response) => {
                        this.items = response.data;
                        if (this.items == 'You are authorised')
                            this.$router.push('/welcome')
                    })
            }
        },
        mounted() {

            this.login()

        }
如果不使用Vue,则可以使用

我将在
mounted
方法中删除对
this.login()
的调用,有关Vue中创建的
mounted
和其他执行挂钩的更好理解,请参阅。 有鉴于此,在提交表单时可能应该调用
登录
方法

阅读上面的生命周期链接后,使用
创建的
钩子测试本地存储支持

让我们首先添加一个标志来表示支持与否

data () {
    return {
        localStorageSupport: true
    }
}
我们假设有支持,然后在
create
上做一个测试,如果实际上没有,我们会在那里更改它

created () {
    try {
        window.localStorage.setItem('the-test-item-name', 'hello-test');
        window.localStorage.removeItem('the-test-item-name');
    } catch (e) {
        console.error('Local storage not supported')
        this.localStorageSupport = false;
    }
}
这样,您可以回退到另一种在客户端上保存信息的方法,例如常规cookie

现在,在创建的
方法中,您已经可以看到如何设置
setItem(名称、内容)
,以及如何删除
removietem(名称)
一个项目,要获得一个项目,只需
getItem(名称)

因此,当您从
$http.post
收到响应时,您需要
setItem
来存储一个值,指示用户是否登录,并且您需要使用
getItem
在要限制的路由上检查该值

.then((response) => {
    this.items = response.data;
    if (this.items == 'You are authorised') {
        // remember, you can check our flag this.localStorageSupport to use a fallback method here
        localStorage.setItem('logged-in', true)
        this.$router.push('/welcome')
    }
})

安装组件时,如何从输入中获取用户名和密码?如果要使用localStorage,则需要检查localStorage数据,以查看用户是否经过身份验证。你可以在这里查看localStorage。谢谢你的回复,太好了。您能否澄清如何在登录后获取项目和限制登录页面。您是否使用VueRouter?检查导航卫士,beforeEnter可能是您需要连接的。如果它是一个不同的路由器,类似的概念也适用,可能是一个不同的名称,但它们会在路由之前触发一些东西。导航卫士链接自发布以来发生了更改,这是新的