Vue的全局組件

Vue是一個組件化開發的框架,一般我們在項目中使用組件的步驟是這樣的。

1.創建一個組件:

比方說我們現在新建一個demo.vue文件,隨便寫一行代碼。

  <template>
    <div>
        <h1>{{msg}}</h1>    
    </div>    
</template>

<script>
export default {
    data() {
        return {
            msg:'只是新創建的一個組件'
        }
    }
}
</script>

2.使用組件

在我們需要使用組件的地方,引入之前寫好的組件,並通過components綁定,就可以直接使用了。

<template>
  <div id="app">
    <demo></demo>
  </div>
</template>

<script>
import demo from './components/demo/demo.vue'
export default {
 components: {
  demo //等價與demo:demo,es6語法
 }
}
</script>

從上述的例子可以看出,我們使用組件,需要經過引入,綁定兩個步驟。那麼,如果我們需要使用一些全局組件或者第三方的組件庫怎麼辦呢?

比如我們要用一些第三方的組件庫(以element-ui爲例),當然最簡單的辦法就是直接引用,在idnex.html上或者是我們需要的頁面,直接通過link引入。

截於elemrnt-ui官網

官網還提供了另一種引入方式(在引用之前需要使用npm安裝一下)。

 

截於elemrnt-ui官網

而且還可以按需引入。(按需引入需要安裝 babel-plugin-component)

 

現在我們知道了使用組件,有兩種方式。一種是引入文件,通過components綁定來使用。另一是引入文件,通過Vue.use()來使用。

那麼自己寫的組件,如何通過vue.use()來使用呢?

1.先創建一個組件

<template>
    <div>
        {{msg}}
    </div>    
</template>
<script>
export default {
    data() {
        return {
            msg:'loading......'
        }
    }
}
</script>

2.在組件的同級目錄下,再創建一個idnex.js文件(名字可以隨便起)

import LoadingComponents from './loading.vue';

const loading = {
    install:function(Vue) {
        Vue.component('Loading', LoadingComponents)
    }
}

export default loading;

3.引入自定義組件,並使用

import Vue from 'vue'
import App from './App.vue'
import loading from './components/loading/'

Vue.use(loading);

new Vue({
  el: '#app',
  data:{
    eventHub: new Vue()
  },
  render: h => h(App)
})

現在就可以在任何地方,直接使用自定義的組件。

<loading></loading>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章