vuex和vue-router全家桶

vuex

关键词:state,getters,actions,mutations,store。

  • state为状态的参数。

  • getters为获取器,用于过滤的方法获取参数。

  • mutations是改变状态参数的函数,但是不能直接被调用,需要对应的store.commit(可以额外传参数)。

  • actions不是直接修改状态,而是基于mutations,可以执行异步处理

  • store更像一个容器,装着以上的所有函数和参数,最后需要注入到Vue的实例当中。

    2.0 特性--辅助函数

    辅助函数j就是可用可不用。如果你用了,它就会提高代码编写效率的。

    • mapState
    • mapGetter
    • mapMutation

    举个例子,如果不用辅助函数mapState

    computed: {
        count () {
          return this.$store.state.count
        }
      }

    使用辅助函数mapState

    computed: mapState([
      // 映射 this.count 为 store.state.count
      'count'
    ])

    如果不用辅助函数mapGetter

    computed: {
      doneTodosCount () {
        return this.$store.getters.doneTodosCount
      }
    }

    使用辅助函数mapGetter

    computed: {
      // 使用对象展开运算符将 getters 混入 computed 对象中
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter',
        ])
      }

    如果不用辅助函数mapMutation

    methods: {
        increment(){
            this.$store.commit('increment')
        },
    }

    使用辅助函数mapMutation

    methods: {
        ...mapMutations([
          'increment',
         ]),
    }

    如果不用辅助函数mapActions

    methods: {
        increment(){
            this.$store.dispatch('increment')
        },
    }

    使用辅助函数mapActions

    methods: {
        ... mapActions([
          'increment',
         ]),
    }

    vue-rounter

  • vue-router的出现不是个意外,也不是让你将所有的路由都装在vue-router。它更多是用于SPA,把一些动态的内容提取出来。例如动态路由。详情请参考官网
    const User = {
      template: '<div>User</div>'
    }
    
    const router = new VueRouter({
      routes: [
        // 动态路径参数 以冒号开头
        { path: '/user/:id', component: User }
      ]
    })

    路由可以针对组件User分配id,js端也可以获取路由的参数。

    const User = {
      template: '<div>User {{ $route.params.id }}</div>'
    }

    关于懒加载

  • 懒加载的功能并非vue特有,而是webpack特有的,有几种特殊的写法
    const Foo = resolve => {
      // require.ensure 是 Webpack 的特殊语法,用来设置 code-split point
      // (代码分块)
      require.ensure(['./Foo.vue'], () => {
        resolve(require('./Foo.vue'))
      })
    }

    也可以简写为

    const Foo = resolve => require(['./Foo.vue'], resolve)

    懒加载会独立分包,把对应的组件独立打包。而懒加载组件的css将不会进行提取。但是会对route-view级别的css进行打包,因此建议将共有的css放在route-view级别。

原文地址:https://www.cnblogs.com/fanting/p/11341833.html