zoukankan      html  css  js  c++  java
  • Vue.use自定义自己的全局组件

     通常我们在vue里面使用别人开发的组件,第一步就是install,第二步在main.js里面引入,第三步Vue.use这个组件。今天我简单的也来use一个自己的组件。

    这里我用的webpack-simple这个简单版本的脚手架为例,安装就不啰嗦了,直接进入正题

    首先看下目前的项目结构:

    webpack首先会加载main.js,所以我们在main的js里面引入。我以element ui来做对比说明

    import Vue from 'vue'
    import App from './App.vue'
    
    // 引入element-ui组件
    import ElementUi from 'element-ui'
    import 'element-ui/lib/theme-default/index.css'
    
    // 引入自定义组件。index.js是组件的默认入口
    import Loading from '../components/loading'
    Vue.use(Loading);
    
    Vue.use(ElementUi);
    new Vue({
      el: '#app',
      render: h => h(App)
    })

    然后在Loading.vue里面定义自己的组件模板

    <!-- 这里和普通组件的书写一样 -->
    <template>
        <div class="loading">
            loading...
        </div>
    </template>

    在index.js文件里面添加install方法

    import MyLoading from './Loading.vue'
    // 这里是重点
    const Loading = {
        install: function(Vue){
            Vue.component('Loading',MyLoading)
        }
    }
    
    // 导出组件
    export default Loading

    接下来就是在App.Vue里面使用组件了,这个组件已经在main.js定义加载了

    <template>
      <div id="app">
      <!-- 使用element ui的组件 -->
      <el-button>默认按钮</el-button>
    
      <!-- 使用自定义组件 -->
      <Loading></Loading>
      </div>
    </template>

    下面是效果图

  • 相关阅读:
    前端导出excel文件
    promise和async/await的用法
    vue element 导出 分页数据的excel表格
    mac net.core 安装问题总结
    npm报MSBUILD错误的解决办法
    现大前端开发环境配置
    git 常用命令
    NodeJs (一)
    VUE 组件通信、传值
    vue-cli 第一章
  • 原文地址:https://www.cnblogs.com/yesyes/p/6658611.html
Copyright © 2011-2022 走看看