Vue.js如何在单个文件组件vue中使用localstorage

时间:2018-05-22 12:39:02

标签: laravel-5 vuejs2

我是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()

        }

1 个答案:

答案 0 :(得分:1)

如果您不使用Vue,可以使用localStorage

我会删除this.login()方法中对mounted的调用,有关createdmounted以及其他执行挂钩的更好理解,请参阅Vue lifecycle Vue公司。 鉴于此,在提交表单时,可能应该调用login方法。

阅读上面的生命周期链接后,使用created挂钩测试localStorage支持。

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

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;
    }
}

通过这种方式,您可以回退到另一种在客户端保存信息的方法,例如:常规饼干。

现在,在created方法中,您已经可以看到如何设置setItem(name, content),并删除removeItem(name)项目,以获取项目,它只是getItem(name)。< / p>

因此,当您从$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')
    }
})
相关问题