vuex-persistedstate简单使用

564 阅读1分钟

插件地址:github.com/robinvdvleu…

效果:

image.png

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <p>{{ count }}</p>
        <p>
            <button @click="increment">+</button>
            <button @click="decrement">-</button>
        </p>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.7/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vuex/3.2.0/vuex.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vuex-persistedstate/3.2.0/vuex-persistedstate.umd.min.js"></script>
    
    <script>
        const store = new Vuex.Store({
            state: {
                count: 0
            },
            plugins: [createPersistedState()],
            mutations: {
                increment: state => state.count++,
                decrement: state => state.count--
            }
        });

        new Vue({
            el: '#app',
            computed: {
                count() {
                    return store.state.count;
                }
            },
            methods: {
                increment() {
                    store.commit('increment');
                },
                decrement() {
                    store.commit('decrement');
                }
            }
        });
    </script>
</body>

</html>