美文网首页前端VueJS计算机
vue.js - 工程实践Tips

vue.js - 工程实践Tips

作者: 红薯爱帅 | 来源:发表于2018-10-14 19:14 被阅读2次

    1. 全局变量

    1.1. Vuex,全局单一状态树State

    import {mapState, mapActions, mapGetters} from 'vuex';
    
    computed: {
      ...mapState('transaction', {state: 'transactionLayerSku'}),
      ...mapGetters('cabinet', ['cabinets'])
    }
    

    1.2. Vue.config,process.env

    Vue.config.productionTip = process.env.NODE_ENV === 'production';
    

    process.env属性,返回一个包含用户环境信息的对象,即当前用户的系统env
    http://nodejs.cn/api/process.html#process_process_env

    1.3. Vue-router => url 参数

    • template跳转
    <router-link :to="{name:'board-users',
                               params: {tid: queryParams.serial_id},
                               query:{customerID: scope.row.user_id}}">
      {{scope.row.user_id}}
    </router-link>
    
    • js跳转
    this.$router.push({
      path: "/start_task",
      query: { taskType: "uncaptured", instructionId: task.id }
    });
    this.$router.go(-1);
    
    • js获取query参数,以及修改
    computed: {
      currentTab: {
        get() {
          const {$route: {query: {currentTab}}} = this;
          if (_.isNil(currentTab)) {
            return 'details';
          }
          return currentTab;
        },
        set(value) {
          const {$route: {query}} = this;
          this.$router.replace({
            query: {...query, currentTab: value}
          });
        }
      }
    }
    

    1.4. Vue 外状态 => 屏幕宽度 => 事件

    获取屏幕宽度 捕获屏幕宽度变化

    1.5. Cookie

    import Cookies from 'js-cookie'
    Cookies.set('username', 'currentUserName')
    Cookies.remove('username')
    let menu = JSON.parse(Cookies.get('my_menu'))
    

    使用全局变量,有助于对components进行拆分,推荐使用1.3. URL参数

    2. 如何复用组件逻辑

    • slot
      场景:图片懒加载组件
      实现加载过程转菊花,加载失败显示失败提示

    • slot-scope
      场景: 瀑布流组件
      复杂布局场景,且子元素必须高度自定义

    • 过滤器filter
      场景:日期按本地时区格式化、OSS图片resize、OSS 图片转CDN链接、货币千分位格式、占位符
      常用过滤器库:vue2-filters、vue-currency-filter

    • 指令
      场景: 实现图片放大镜效果
      修饰符 —— 让调用语法更甜蜜

    • mixins

      • a. 对象浅合并 (一层属性深度),在和组件的数据发生冲突时以组件数据优先
      • b. 同名钩子函数将混合为一个数组
      • c. 我们还可以自定义合并策略

    3. 坑

    • 避免通过prop设置data,可设置computed属性
    • 不要把methods当computed用
    • 不要修改prop值!!!

    4. 规范

    • 组件内状态data,提供默认值
    • 不要在模板中写太多逻辑代码,多用 computed 属性
    • prop 传递的链条不要太深 - 使用slot解耦
    • 尽量为 props 提供完整配置信息

    5. 文档

    官方文档

    组件库

    优秀插件

    优秀demo

    相关文章

      网友评论

        本文标题:vue.js - 工程实践Tips

        本文链接:https://www.haomeiwen.com/subject/koctzftx.html