这里有新鲜出炉的 vue.js 教程,程序狗速度看过来!
Vue.js 是构建 web 界面的 JavaScript 库,提供数据驱动的组件,还有简单灵活的 API,使得 MVVM 更简单。
本篇文章主要介绍了 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>
下面是效果图
来源: http://www.phperz.com/article/17/0826/338669.html