wepack从0开始配置vue环境之三: 集成vuex+vue-router

github传送门
webpack之一webpack基础配置
webpack之二webpack部署优化
webpack之四集成ssr

  • 集成vue-router

  1. 新建/client/config/router.js和/client/config/routes.js
  2. 安装vue-routercnpm i vue-router -S
  3. routes.js用来存放路由映射
import App from '../views/app/App.vue'
import Login from '../views/login/login.vue'

export default [
  {
    path: '/app',
    component: App
  },
  {
    path: '/login',
    component: Login
  }
]

  1. 修改webpack.config.client.js里的HtmlWebpackPlugin({template: path.join(__dirname, './template.html')})然后新建/build/template.html
  2. 在/client/config/router.js中引入vue-router, 导出匿名实例到index.js
import VueRouter from 'vue-router'
import routes from './routes.js'

export default () => {
  return new VueRouter({
    // mode: 'history',
    routes
  })
}

  1. 在/client/index.js中引入vue-router, 通过Vue.use()方法集成插件, 引入router实例, 添加到vue实例中
import Vue from 'vue'
import App from './app.vue'
import VueRouter from 'vue-router'
import '@assets/css/reset.styl'
import createRouter from './config/router'

Vue.use(VueRouter)
const router = createRouter()

new Vue({
  el: '#root',
  router,
  render: h => h(App)
})
  1. 在App组件内 添加<router-view>标签
  • vue-router的选项配置

url的hash模式和history模式: hash路由用来做路由定位, 不做状态记录, 不被浏览器解析, 不利于seo; history

  1. router的选项:
    -- mode: ['hash', 'history', ''], 在使用history模式时, 需要配置webpack-dev-server, 添加historyApiFallBack, 把路由重新定位到index.html, output中的publicPath是需要和historyApiFallBack.index中的路径是相对应的
  historyApiFallback: {
    index: '/public/index.html'
  }

-- routes: 配置路由和组件之间的映射
-- base: '/base/' -> 为path添加一个基路径, 没有base也能跳转
-- linkActiveClass: ' ' -> 路由的不完全匹配, 匹配后, 会在对应的<routet-link>添加一个active类
-- linkExactActiveClass: ' '路由的完全匹配必须一模一样才行,会在对应的<routet-link>添加一个active类
-- scrollBehavior: 用来记录之前浏览网页滚动的位置, to, 和from是route对象

scrollBehavior (to, from, savedPosition) {
  if(savedPosition) {
    return savedPosition
  } else {
    return  {x:0, y:0}
  }
}

-- parseQuery(query){}: 可以自定义query转成json
-- stringifyQuery(){obj}: 可以自动以json转成字符串
-- fallback: 默认true, 在不支持history的浏览器上自动转成hash, 设置成false, 页面会跳转

  1. routes的选项:
    -- name: 命名, 可以通过name跳转
    -- path: 路由的路径
    -- component: 需要渲染的组件
    -- components: 具名router-view中使用, 接受一个对象, 没有name属性的router-view为default
    -- redirect: 路由重定向
    -- meta:obj -> spa用的都是一个html, 无法修改元信息, 通过meta可以储存页面的元信息, 存储在route对象上
    -- children: 设置自路由, 需要加router-view
    -- path: '/app/:id': 路由传参, 通过this.route.params.id获取,route对象包含query, params, meta, name等等还可以通过props传
    -- props: 默认为false, 返回一个对象, 对象的key就是传到组件中的props
  • 1.定义为ture的话, 可以把路由参数作为props传入组件(组件需要定义对应的props), 可以更好的解耦组件,
    1. 还可以直接传值{id: '123'},
    1. 也可以是一个带route参数的函数, route => ({id: route.query.b// route.meta.title 等等})
  1. 路由动画<transition">:一个小套路:
<transition name="v" mode="out-in">
  <router-view></router-view>
</transition>
<style>
  .v-enter-active, .v-leave-active {
    transition: all 0.5s ease-in-out
  }
  .v-enter, .v-leave-to {
    opacity: 0; // fade
    transform: translate3d(-100%, 0, 0) // 右进场动画
  }
</style>
  1. 具名router-view
<router-view></router-view>
<router-view name="top"></router-view>
<router-view name="bottom"></router-view>
routes: [
  {
    path: '/app',
    components: {
      default: App, // 不具名的router-view
      top: AppTop,
      bottom: AppBottom
    }
  }
]
  • 路由导航守卫, 钩子

  1. 全局守卫
    -- 1router.beforeEach(to, from, next) -> 进入路由前, 进行数据校验
    -- 2router.beforeReaolve(to, from, next) -> next(path: '/', replace: true), 他在afterEach之前触发
    -- 2router.afterEach(to, from) -> 进入路由后
  2. routes下的守卫
    -- beforeEnter(to, from, next) -> 进入路由之前, 在beforeEach和beforeResolve()之间
  3. 组件内的守卫
    -- beforeRouteEnter(to, from, next) -> 进入本组件时触发
    -- beforeRouteUpdate(to, from, next) -> 在使用路由参数时, 当同路由参数互相切换时触发
    -- beforeRouteLeave(to, from, next) -> 离开本组件后,触发, 使用场景, 表单中提醒是否确认要离开
    -- 组件内守卫的next参数, 接受一个vue实例, next(vm => { console.log(vm) })
  • 异步组件

  1. 修改/client/config/routes.js
// import App from '../views/app/App.vue'
// import Login from '../views/login/login.vue'

export default [
  {
    path: '/',
    redirect: '/app'
  },
  {
    path: '/app/:id',
    // component: App
    component: import('../views/app/App.vue')
  },
  {
    path: '/login',
    // component: Login
    component: import('../views/login/login.vue')
  }
]
  1. 引入babel插件babel-plugin-syntax-dynamic-import, 在.babelrc里添加此插件,修改routes.js
 component: () => import(/* webpackChunkName: "login-view" */ '../views/login/login.vue')
  • vuex集成

  1. 新建/client/store/store.js
import Vuex from 'vuex'

export default () => {
  return new Vuex.Store({
    state: {
      count: 0
    }
  })
}
  1. 在/client/index.js下配置vuex
import Vue from 'vue'
import App from './app.vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'
import '@assets/css/reset.styl'
import createRouter from './config/router'
import createStore from './store/store'

Vue.use(VueRouter)
Vue.use(Vuex)

const router = createRouter()
const store = createStore()

// router.beforeEach((to, from, next) => {
//   console.log(to)
//   if (to.fullPath === '/app') next({path: '/login', replace: true})
//   else next()
// })

new Vue({
  el: '#root',
  router,
  store,
  render: h => h(App)
})
  • vuex的选项

  1. 基本选项:
    -- strict: 定义为true时, 直接修改state(不通过mutations)会发出警告
    -- state: 存储数据
    -- mutations: 同步改变state
    -- actions: 异步改变state
    -- getters: 相当于computed, 属性值是state为参数的函数
// 配置:
import Vuex from 'vuex'

export default () => {
  return new Vuex.Store({
    state: {
      count: 0,
      first: 'zhang',
      last: 'kay'
    },
    mutations: {
      updateCount (state, count) {
        state.count = count
      }
    },
    actions: {
      updateCountAsync (store, count) {
        setTimeout(() => {
          store.commit('updateCount', count)
        }, 1000)
      }
    },
    getters: {
      fullName: (state) => `${state.first}-${state.last}`
    }
  })
}
//map用法
<template>
  <div>
    <p>count: {{myCount1}}</p>
    <p>name: {{myName}}</p>
    <button @click="myUC(1)">mutation</button><br>
    <button @click="updateCountAsync(10)">action</button>
  </div>
</template>
<script>
import {
  mapState,
  mapActions,
  mapMutations,
  mapGetters
} from 'vuex'
export default {
  computed: {
    // ...mapState(['count']),
    ...mapState({
      myCount: 'count',
      myCount1: state => state.count
    }),
    // ...mapGetters(['fullName'])
    ...mapGetters({
      myName: 'fullName'
    })
  },
  methods: {
    // ...mapMutations(['updateCount']),
    ...mapMutations({
      myUC: 'updateCount'
    }),
    ...mapActions(['updateCountAsync'])
  }
}
</script>
  1. modules的应用
    -- 未使用namespaced参数之前, mutations, actions, getters是注册到全局命名空间的, 但是mutations里的state是module内的,用法与全局的一直
<template>
  <div>
    <p>aText: {{aText}}</p>
    <p>_text: {{_text}}</p>
  </div>
</template>
<script>
import {
  mapState,
  mapMutations,
  mapActions,
  mapGetters
} from 'vuex'
export default {
  computed: {
    ...mapState({
      aText: state => state.a.text
    }),
    ...mapGetters({
      _text: '_text'
    })
  },
  methods: {
    ...mapMutations(['updateA']),
    ...mapActions(['updateAAsync'])
  },
  mounted () {
    console.log(this.$store.state.a.aText)
    this.updateA('xxx')
    this.updateAAsync({
      text: 'action - a',
      time: 2000
    })
  }
}
</script>

-- 使用namespaced的module,使用actions, mutations, getters,的注册需要以路径的形式, 如下, bModule为启动namespaced的模块

<template>
  <div>
    <p>aText: {{aText}}</p>
    <p>a的_text: {{a_text}}</p>
    <p>bText: {{bText}}</p>
    <p>b的_text: {{b_text}}</p>
  </div>
</template>
<script>
import {
  mapState,
  mapMutations,
  mapActions,
  mapGetters
} from 'vuex'
export default {
  computed: {
    ...mapState({
      aText: state => state.a.text,
      bText: state => state.b.text
    }),
    ...mapGetters({
      a_text: '_text',
      b_text: 'b/_text'
    })
  },
  methods: {
    ...mapMutations(['updateText', 'b/updateText']),
    ...mapActions(['updateTextAsync', 'b/updateTextAsync'])
  },
  mounted () {
    console.log(this.$store.state.a.aText)
    this.updateText('mutations - a')
    this.updateTextAsync({
      text: 'actions - a',
      time: 2000
    })
    this['b/updateText']('mutations - b')
    this['b/updateTextAsync']({
      text: 'actions - b',
      time: 2000
    })
  }
}
</script>

-- 模块的actions可以调用全局mutations, 通过commit('mutations', data, {options})的第三个参数配置为{root: true}

 methods: {
    ...mapMutations(['updateText', 'b/updateText']),
    ...mapActions(['updateTextAsync', 'b/updateTextAsync', 'b/updateCountAsync'])
  },
// ...
this['b/updateCountAsync']()
store.js的配置如下
import Vuex from 'vuex'

const isDev = process.env.NODE_ENV === 'development'

export default () => {
  return new Vuex.Store({
    strict: isDev,
    state: {
      count: 0,
      first: 'zhang',
      last: 'kay'
    },
    mutations: {
      updateCount (state, count) {
        state.count = count
      }
    },
    actions: {
      updateCountAsync (store, count) {
        setTimeout(() => {
          store.commit('updateCount', count)
        }, 1000)
      }
    },
    getters: {
      fullName: (state) => `${state.first}-${state.last}`
    },
    modules: {
      a: {
        state: {
          text: 'aaaa'
        },
        mutations: {
          updateText (state, text) {
            state.text = text
          }
        },
        actions: {
          updateTextAsync ({commit}, {text, time}) {
            setTimeout(() => {
              commit('updateA', text)
            }, time)
          }
        },
        getters: {
          _text: state => state.text + '-getters'
        }
      },
      b: {
        namespaced: true,
        state: {
          text: 'bbb'
        },
        mutations: {
          updateText (state, text) {
            state.text = text
          }
        },
        actions: {
          updateTextAsync ({commit, state, rootState}, {text, time}) {
            setTimeout(() => {
              commit('updateText', text + rootState.first)
            }, time)
          },
          updateCountAsync ({commit, state, rootState}) {
            commit('updateCount', state.text, {root: true})
          }
        },
        getters: {
          // 可以使用全局的getters和全局state
          _text: (state, getters, rootState) => state.text + 'b-getters -  '
        }
      }
    }
  })
}
  1. vuex动态加载子模块: 调用store.registerModule('c', { state, mutations, actions, getters})
  2. vuex的热重载:1. 将Store实例赋值给一个变量store 2. 使用module.hot.accept([], () => { 3. 在回调里调用store.hotUpdate({更新模块})}), 学modules的模块时需要注意, 加上modules
import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import actions from './actions/actions'
import getters from './getters/getters'
import a from './a'
import b from './b'

const isDev = process.env.NODE_ENV === 'development'

export default () => {
  const store = new Vuex.Store({
    strict: isDev,
    state: defaultState,
    mutations,
    actions,
    getters,
    modules: {
      a,
      b
    }
  })
 
  if (module.hot) {
    module.hot.accept([
      './state/state',
      './mutations/mutations',
      './actions/actions',
      './getters/getters',
      './a',
      './b'
    ], () => {
      const newState = require('./state/state').default
      const newMutations = require('./mutations/mutations').default
      const newActions = require('./actions/actions').default
      const newGetters = require('./getters/getters').default
      const newA = require('./a').default
      const newB = require('./b').default

      store.hotUpdate({
        state: newState,
        mutations: newMutations,
        actions: newActions,
        getters: newGetters,
        modules: {
          a: newA,
          b: newB
        }
      })
    })
  }
  return store
}

vuex热重载总结: 通过webpack自带的module.hot.accept([], () => {})方法和vue的store.hotUpdate({}); module.hot.accept()第一个参数是一个数组, 存储这需要热重载的模块的路径, 第二个参数是一个回调韩式, 在这里从新引入[]里的模块, 在通过store.hotUpdate()方法重新赋值

 if (module.hot) {
    module.hot.accept([
      './state/state',
      './mutations/mutations',
      './actions/actions',
      './getters/getters',
      './a',
      './b'
    ], () => {
      const newState = require('./state/state').default
      const newMutations = require('./mutations/mutations').default
      const newActions = require('./actions/actions').default
      const newGetters = require('./getters/getters').default
      const newA = require('./a').default
      const newB = require('./b').default

      store.hotUpdate({
        state: newState,
        mutations: newMutations,
        actions: newActions,
        getters: newGetters,
        modules: {
          a: newA,
          b: newB
        }
      })
    })
  }
  1. vue的一些其他的API
    -- store.unregisterModule('a'): 卸载模块
    -- store.watch((state) => state.count + 1, (newCount) => {执行完前一个函数后调用 })
    -- store.subscribe(mutation, state) => { mutation.type, mutaion.payload(参数)} : 用来监听mutation的调用情况, 可以打日志
    -- store.subscribeAction(action, state) => {action.type, action.payload(参数)}
    -- plugins: vuex实例里的一个选项, 类似(state啥的), 值为一个数组, 数组内的每一项为一个带store参数的函数
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 目录 一、项目结构的核心思想 二、项目目录结构 三、资源路径编译规则 四、index.html 五、build目录...
    科研者阅读 11,230评论 0 40
  • vue-cli搭建项目 确保安装了node与npm 再目标文件夹下打开终端 执行cnpm i vue-cli -g...
    Akiko_秋子阅读 3,189评论 1 22
  • 1路由,其实就是指向的意思,当我点击页面上的home按钮时,页面中就要显示home的内容,如果点击页面上的abou...
    你好陌生人丶阅读 1,578评论 0 6
  • 今日大盘低开低走,尾盘收出一根小阳十字星,成交量萎缩。盘面上看,风沙治理、油气改革、网贷概念、奢侈品、海水淡化等概...
    赢家说_4d25阅读 132评论 0 0
  • 心灵胜过一切。 如果你有内在的和平, 那么无论发生什么,你都会安然。 ~马修.理查德
    心中境地阅读 95评论 0 0