解讀Vue組件注冊方式
組件化的概念讓前端頁面開發有了更清晰的結構。
Vue 中的組件就是一個 Vue 的實例對象。因此,Vue 組件的構造選項和 new Vue() 方法構造 Vue 實例的構造選項是一樣的,其可接收的構造選項都是一樣的。除了 el 這樣 根實例 特有的選項。但是,Vue 組件必須得是可以復用的,因此,就必須要求構造選項中的 data 選項必須是一個函數,該函數返回一個對象。
為什么 data 選項是個返回對象的函數就可以保證組件的可復用性呢?
因為無論是 new Vue() 的方式還是定義 Vue組件 的方式創建一個 Vue 實例,其執行的操作都是將構造選項中的各屬性值直接賦值給新創建的 Vue 實例對象。組件復用就是 Vue 使用 相同的構造選項 構造出多個同名不同地址的 Vue 實例對象。如果 Vue 組件定義時的構造選項中的 data 選項是一個對象,那么在組件復用時,多個組件就會共用一個 data 數據對象,因為是直接將 data 對象的地址賦值給組件的 Vue 實例的。但如果組件定義時的 data 選項是一個函數的話,那么 Vue 根據構造選項創建組件時會執行該函數從而得到一個對象。這樣一來,每次創建 Vue 實例時的 data 對象都是重新生成的,因此,多個組件都有各自的 data 數據對象,不會相互影響。
實際上,在組件注冊時是在定義組件的構造選項,在組件使用時才真正創建對應的 Vue 組件實例。
1 、全局注冊全局注冊的組件可以在 Vue 根實例和所有的子組件中使用。注冊入口為Vue.component()函數,一次注冊,隨時使用,注冊方式如下:
Vue.component(’my-component-name’,{ options })
示例如下:
//main.js//此示例是在 vue-cli 創建的項目,默認是非完整版vue,無法用 template 選項,因此使用 render 函數寫組件內容。Vue.component(’all-test’,{ data(){ return { x: ’我是全局組件’ } }, render(h){ return h(’div’,this.x) }})//全局注冊的組件直接使用即可//App.vue<template> <div id='app'> <all-test /> </div></template>2 、局部注冊
局部注冊是通過一個普通的 JavaScript 對象來定義組件。然后組件的命名和注冊入口是在 Vue實例 構造選項中的 components 選項。
let component = { options }//new Vue 創建的根元素 Vue 實例new Vue({ el: ’#app’ components: {’my-component-name’: component }})//或注冊 Vue組件 創建的 Vue 實例export default { components: {’my-component-name’: component }}
示例如下:
//App.vue<template> <div id='app'> <all-test /> <component-a /> <component-b /> </div></template><script>let ComponentA = { data(){ return { x: ’我是局部組件 A’ } }, render(h){ return h(’div’,this.x) }}export default { name: ’App’, components: { ’component-a’: ComponentA, ’component-b’: {data(){ return { x: ’我是局部組件 B’ }},render(h){ return h(’div’,this.x)} } }}</script>3 、模塊系統中局部注冊
在使用了諸如 Babel 和 webpack 的模塊系統中可以使用 import 和 export 的方式單獨導入組件的構造選項對象 或者 導入對應構造選項的 *.vue 文件。
//c.jsexport default { data(){return { x: ’我是 c.js 文件單獨導出的組件構造選項對象’} }, render(h){return h(’div’,this.x) }}//D.vue<template> <div>{{x}} </div></template><script>export default { data(){return { x: ’我是 D.vue 文件導出的組件’} }}</script>//App.vue<template> <div id='app'> <C /> <D /> </div></template>import C from ’./c.js’import D from ’./components/D.vue’export default { name: ’App’, components: { C, D }}</script>
以上就是解讀Vue組件注冊方式的詳細內容,更多關于Vue組件注冊方式的資料請關注好吧啦網其它相關文章!
相關文章: