H5技术栈前端xuexivue

Vue.use()注册自定义组件(简易版)

2018-03-08  本文已影响57人  茶树菇小学生

前言


正文

    <template lang="html">
      <div class="">
        {{ data }}
      </div>
    </template>
    
    <script>
    export default {
      name: 'loading',
      data() {
        return {
          data: 'loadig...'
        }
      }
    }
    </script>
    
    <style lang="css">
    </style>
    import myLoading from './Loading'
    
    //方法一:这种方法很简单,需要使用使用时,直接在使用的地方加上<Loading/>标签就行
    const Loading = {
      install: function(vue) {
        vue.component('Loading', myLoading)
      }
    }
    
    // 方法二:这种是直接显示,在显示该组件是可以加设条件判断,让组件在特定的条件下显示(诸如 提示弹框)
    const Loading = {
      install: function(vue) {
        vue.component('Loading', myLoading)
        const LoadingObj = vue.extend(myLoading)
        let vm = new LoadingObj({
          el: document.createElement('div')
        })
        console.log(vm);
        document.body.appendChild(vm.$el)
      }
    }
    // 导出组件
    export default Loading

import Vue from 'vue'
import App from './App'
//这里从loading文件中默认倒入index.js文件
import Loading from './components/loading'

Vue.use(Loading)

export const $vueApp = new Vue({
  el: '#app',
  render: h => h(App),
  components: { App },
  template: '<App/>'
})

如果采用第二种方法到这了页面已经显示你设置的全局组件
如果采用第一种方法还需要在想要显示的组件中直接使用<Loading/>标签即可

Vue简单只是在于上手容易,高阶用法很多,还需要努力

上一篇下一篇

猜你喜欢

热点阅读