Vue语法总结

Posted by Shen Chaoran on July 2, 2019

构造函数

new Vue({
    el: String,
    data: {
        [key: string]: any              // view 中可以绑定的 数据,相当于 angular 中的属性
    },
    methods: {                          // view 中可以调用的 函数,相当于 angular 中的方法
        [key: string]: Function
    },
    computed: {                         // 计算属性,相当于 angular 中的 getter,与 methods 相比有缓存
        [key: string]: Function
    },
    watch: {                            // 侦听属性,相当于 Observable 和 ngOnchanged,注意对于复杂类型的监听,用深度监听或结合 immutable js
        [key: string]: (newV?, oldV?) => {}
    },
    render: (createElement: () => VNode) => VNode,      // JSX 语法
    components: {                       // 局部注册的组件
        [key: string]: Component,   
    },
    directives: {                       // 局部注册的指令
        [key: string]: Directive,
    },
    filters: {
        [key: string]: Filter,          // 局部注册的过滤器
    }
})

模板语法

  • v-if, v-else, v-else-if
  • v-for
  • v-model: 双向绑定
  • v-one
  • v-html
  • v-bind:[prop-name] or :[prop-name]: 父子组件传递——属性绑定
  • v-bind:[attr] or :[attr]: id, href, disabled, class, style, key
  • v-on:[event] or @[event]
  • v-show: 切换 display 样式

变化检测

数组

VUE 组件

VUE.component('component-name', {
    data: Object | () => Object,
    template: String,
})

生命周期

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • deactivated
  • beforeDestroy
  • destroyed

computed & watch & methods

  • watch 监控的必须是 data 里的属性,可以执行异步方法
  • computed 监控的必须不在 data 里
  • methods 纯函数

  • 前端代码审查: eslint
  • 不规则代码自动fix:
    • vue:
      • vscode 环境: vetur + eslint + prettier
      • webstorm 环境: eslint