stack.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Vue from 'vue'
  2. import router from '../router'
  3. export default {
  4. install (vue) {
  5. const stack = {
  6. list: {},
  7. query: {},
  8. }
  9. const actions = {}
  10. const method = {
  11. create (name, title, query = {}) {
  12. stack.list[name] = [{ name, title }]
  13. stack.query[name] = { [name]: query }
  14. this.emit(name)
  15. },
  16. push (name, title = '未命名', query = {}, routeName = router.history.current.name) {
  17. const currentStackList = stack.list[routeName]
  18. const currentStackQuery = stack.query[routeName]
  19. if (!currentStackList) return new Error(`没有找到${routeName}的栈`)
  20. currentStackList.push({ name, title })
  21. currentStackQuery[name] = query
  22. this.emit(routeName)
  23. },
  24. replace (name, title, query = {}, routeName = router.history.current.name) {
  25. this.go(-1, routeName, false)
  26. this.push(name, title, query)
  27. },
  28. go (backward = -1, routeName = router.history.current.name, emit = true) {
  29. const currentStackList = stack.list[routeName]
  30. if (!currentStackList) return new Error(`没有找到${routeName}的栈`)
  31. if (currentStackList.length === 1) return
  32. currentStackList.length += backward
  33. if (emit) this.emit(routeName)
  34. },
  35. emit (name) {
  36. Vue.hub.$emit('STACK_CHANGE', {
  37. list: stack.list[name],
  38. query: stack.query[name],
  39. })
  40. // console.group('Stack Change:')
  41. // console.log(stack)
  42. // console.groupEnd('Stack Change:')
  43. },
  44. addAction (name, action, payload = {}, option = {}) {
  45. if (!name || !action) return new Error('栈名和action是必须参数')
  46. actions[name] = { action, payload, option }
  47. Vue.hub.$emit('STACK_ACTION', actions)
  48. // console.group('Stack Action:')
  49. // console.log(actions)
  50. // console.groupEnd('Stack Action:')
  51. },
  52. getStack () {
  53. return stack
  54. },
  55. }
  56. vue.prototype.$stack = method
  57. vue.stack = method
  58. },
  59. }