跟随Element学习Vue小技巧——Vue

190 阅读3分钟

结束

意味着新的开始

1 组件要素

props

技巧总结

1.Function类型,构建 format
2.Object类型,构建 VNode
3.集体绑定,v-bind,多用于属性和事件中转$listeners-$attrs

event

技巧总结

1.事件传参,argument
2.事件传递,dispatch
3.双向绑定,update:xxx

slot

技巧总结

1.插槽语法糖,#default
2.插槽JSX,JSX-slot
3.函数式组件,Scoped Slots



2 组件复用

mixin

技巧总结

1.混入文件,不止js,还可以混入组件
2.混合增强,在原文件中新增属性方法
3.混入传参,导出函数返回对象

directive

技巧总结

1.属性传参,参数不止value,arg,modifier还可以是attrs
2.动态插入组件,在DOM元素里挂载另一个组件

filter

技巧总结

1.全局过滤器,处理空值,字符转换

JSX

技巧总结

1.事件修饰,模拟vue事件修饰
2.指令绑定,模拟vue指令

extend

技巧总结

1.增强组件,扩展组件属性和方法

plugin

技巧总结

1.批量构建组件,开发插件



3 组件边界

组件查找

技巧总结

1.$root, 查找根组件,可构建$bus
2.provide-inject,查找祖先,后代
3.$parent-$children,查找父子组件
4.$refs,查找指定组件
5.__vue__查找el挂载组件

组件缓存

技巧总结

1.keep-alive
2.v-show,显示隐藏

组件刷新

技巧总结

1.绑定key值
2.v-if,销毁重建
3.$forceUpdate, 强制刷新

组件语法糖

技巧总结

1.v-bind=“obj”, 属性集体绑定
2.#file=“fileInfo”, 作用域插槽简化
3.v-model, :value @input简化
4..sync.v, :v @update:v简化
5.this.$once('hook:beforeDestroy', fn) 事件侦听器



4 工具箱

autoprefixer

/*
* @{desc} 添加前缀
* @{params} style 样式
*/
export const autoprefixer = function(style) {
  if (typeof style !== 'object') return style;
  const rules = ['transform', 'transition', 'animation'];
  const prefixes = ['ms-', 'webkit-'];
  rules.forEach(rule => {
    const value = style[rule];
    if (rule && value) {
      prefixes.forEach(prefix => {
        style[prefix + rule] = value;
      });
    }
  });
  return style;
};

firstUpperCase

/*
* @{desc} 首字母大写
* @{params} str:String
* @{example} 
  firstUpperCase('home') =>Home
*/
const firstUpperCase = str => {
  return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
};

kebabCase

/*
* @{desc} 首字母大写
* @{params} str:String
* @{example} 
  kebabCase('BaseNav') =>base-nav
*/
export const kebabCase = function(str) {
  const hyphenateRE = /([^-])([A-Z])/g;
  return str
    .replace(hyphenateRE, '$1-$2')
    .replace(hyphenateRE, '$1-$2')
    .toLowerCase();
};

navigator

export const isIE = function() {
  return !Vue.prototype.$isServer && !isNaN(Number(document.documentMode));
};

export const isEdge = function() {
  return !Vue.prototype.$isServer && navigator.userAgent.indexOf('Edge') > -1;
};

export const isFirefox = function() {
  return !Vue.prototype.$isServer && !!window.navigator.userAgent.match(/firefox/i);
};

mixColor

/*
* @{desc} 颜色加深或减淡
* @{params} 
    color:String #fff | #ffffff
    percent:Number 0.2 | -0.2
* @{example}
  // 加深
  mixColor('#fff', 0.2) 
  =>rgb(255 * 0.8, 204, 204)
*/
mixColor(color, percent) {
  let { red, green, blue } = this.getColorChannels(color);
  if (percent > 0) { // shade given color
    red *= 1 - percent;
    green *= 1 - percent;
    blue *= 1 - percent;
  } else { // tint given color
    red += (255 - red) * percent;
    green += (255 - green) * percent;
    blue += (255 - blue) * percent;
  }
  return `rgb(${ Math.round(red) }, ${ Math.round(green) }, ${ Math.round(blue) })`;
}



在Ta没来之前 你本来就是一个人

参考链接

往期回顾