vue 頂級組件

有時候懶的把一些通用組件寫到template裏面去,而業務中又須要用到,好比表示loading狀態這樣組件。vue

若是是這樣的組件,能夠選擇把組件手動初始化,讓組件在整個app生命週期中始終保持活躍。api

如:app

// a.js
import Vue from 'vue'

import hello from './hello.vue'


  const wrapInstance = new Vue({
    render(h) {
      return h(hello, {})
    }
  })

  const wrap = wrapInstance.$mount() // 渲染成DOM
  document.body.appendChild(wrap.$el) // 把DOM插入節點
  const helloInstance = wrapInstance.$children[0] // 拿到的是當前的vue實例,hello實例是當前的子組件
export default helloInstance
// main.js
import helloInstance from 'a.js'
Vue.prototype.$someName = helloInstance

實例化一個vue組件,掛在到原型鏈 或者 項目root vue實例上,就能夠經過函數式的調用組件的方法。在APP生命週期內能夠永不摧毀,方便調用。函數

相似Element組件庫的loading組件 或者 message組件。post

this.$message.error('錯了哦,這是一條錯誤消息')經過函數就能夠調用Message組件方法。this

在線實例
element文檔地址.net

若是是一些全局性的組件,或者頂層組件,就能夠考慮在生命週期永久實例化,綁定在VUE的原型上,方便開發的時候調用。prototype

相關文章
相關標籤/搜索