uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

vuex #202

Open uniquejava opened 6 years ago

uniquejava commented 6 years ago

在actions中返回Promise? Returning Promises from Vuex actions

Persist Vuex

npm install vuex-persistedstate

How does this work? https://github.com/robinvdvleuten/vuex-persistedstate/issues/30

persist in cookie

session cookie不太好用(cookie如果不指定age默认就是session cookie:关闭窗口即失效) 但是session cookie在刷新页面时也会失效, 并不是我想要的.

mport { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
});

persist in sessionStorage

原来除了localStorage外还有sessionStorage, sessionStorage在当前tab页中有效.

import createPersistedState from 'vuex-persistedstate';
const store = new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  plugins: [createPersistedState({
    storage: window.sessionStorage
  })],
  state: initialState(),
  getters: {},

Vue Event Bus

Sometimes you need a quick and easy solution to pass data between Vue.js components.

定义

// event-bus.js
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;

使用

EventBus.$emit('EVENT_NAME', payLoad);
EventBus.$on(‘EVENT_NAME’, payLoad=>{})

// Listen to the event.
EventBus.$on('i-got-clicked', clickHandler);
// Stop listening.
EventBus.$off('i-got-clicked', clickHandler);
// Remove every single listener from EventBus
EventBus.$off()

References

  1. Creating a Global Event Bus with Vue.js
  2. A simple EventBus to communicate between Vue.js components
uniquejava commented 6 years ago

setTimeout

Vuex: How to do a state change in setTimeout() callback