Vue整理(1.0.0)

228 阅读2分钟
组件生命周期
  • 如图示:

    image
    image

  • 组件嵌套时生命周期


beforeCreate-parent
created-parent      
//已经可以获取data数据,dom还未渲染,不可进行dom操作;需要操作dom,写在nextTick()回调函数中
beforeMount-parent  //创建了dom结构,绑定的数据还未被替换

beforeCreate-children
created-children     //可以获取父组件传递过来的值
beforeMount-children
mounted-children   //子组件编译为dom结构

mounted-parent     //父组件编译为dom结构,数据绑定替换
//所有dom挂载和渲染都已经完成,可进行dom操作

vue生命周期在真实场景下的业务应用

  • created:进行ajax请求异步数据的获取、初始化数据
  • mounted:挂载元素内dom节点的获取
  • nextTick:针对单一事件更新数据后立即操作dom
  • updated:任何数据的更新,如果要做统一的业务逻辑处理
  • watch:监听具体数据变化,并做相应的处理,执行异步或开销比较大的处理时

组件通信
  • 父传子
    • props
      • 子组件可以响应父组件数据变化
      • 子组件不能修改数据(单向数据流)
  • 子传父
    • 事件传递
      • 子组件发射事件:$emit('send-event'),父组件注册@send-event="fn"
      • 通过props传递一个父组件的回调函数到子组件
  • 兄弟组件
    • 事件总线方法
      • 使用一个共同的eventBusVue对象
//event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

//main.js
Vue.prototype.$EventBus = new Vue()

组件全局注册
Vue.component('my-component-name', {
  // ... 选项 ...
  data: function(){
      return {
          
      }
  }
})
全局注册的组件可以用在其被注册之后的任何通过new Vue创建的实例中
组件局部注册
var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }

new Vue({
  el: '#app',
  components: {
    'component-a': ComponentA,
    'component-b': ComponentB
  }
})

模块系统中注册
import ComponentA from './ComponentA'
import ComponentC from './ComponentC'

export default {
  components: {
    ComponentA,
    ComponentC
  },
  // ...
}

【Vue插件写法】
  • 声明插件
  • 写插件
  • 注册插件
  • 使用插件
1.插件注册
// 调用 `MyPlugin.install(Vue)`
//在根实例之前注册插件
import MyPlugin from './MyPlugin.js'
Vue.use(MyPlugin)

new Vue({
  //... options
})
2.自定义插件写法
//自定义插件提供一下四种写法

MyPlugin.install = function (Vue, options) {
  
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}