美文网首页
vue项目与element-ui结合使用

vue项目与element-ui结合使用

作者: 追风筝的一朵云 | 来源:发表于2019-11-19 15:49 被阅读0次

    项目创建好了,我们开始使用。提到vue一般大家都会想到与element-ui结合使用,方便我们在日常的工作中使用elment,节约时间,同时,用起来也是比较灵活的。下面我们来引用element-ui。

    1.打开cmd,进入到当前刚创建的vue项目目录

    执行命令:cd 你的项目目录路径地址(mac的话只要选中你的项目文件,按住option + command + c就可以复制项目路径地址了,然后command + v 粘贴过去回车就到你想要的目录下面了)

    项目目录路径地址

    2.在当前目录中运行:npm install element-ui -S

    然后我们可以打开项目,查看package.json文件下有没有element-ui如图:

    查看element-ui安装结果

    然后我们把引用的方式分为按需引入,和全局引入。

    @-1.按需引入:有时候项目中只用到ElementUI中的几个组件,全局引入会增加项目体积,所以按需引入更合适。(你也可以选择在你页面中的script里面import。这种的引入方式,只作用于你当前的页面。)

    引入

    在main.js中引入并注册组件

    import Vue from 'vue';

    //引入按钮组件(Button)和下拉选择器组件(Select)

    import { Button, Select } from 'element-ui';

    import App from './App.vue';

    //注意:样式文件需要单独引入

    import 'element-ui/lib/theme-chalk/index.css';

    //将引入的组件注册为全局Vue组件

    Vue.component(Button.name, Button);

    Vue.component(Select.name, Select);

    /* 或写为

    * Vue.use(Button)

    * Vue.use(Select)

    */

    new Vue({

      el: '#app',

      render: h => h(App)

    });

    使用

    我们已经将Elementui组件注册为了Vue组件,就可以在Vue页面中使用组件,但是,需要注意的是,样式文件需要单独引入,上面已经引入了样式文件,下面就可以是使用了

    <template>

      <div id="app">

            <el-button type="primary">主要按钮</el-button>

            <el-button type="success">成功按钮</el-button>

            <el-button type="info">信息按钮</el-button>

            <el-button type="warning">警告按钮</el-button>

            <el-button type="danger">危险按钮</el-button>

      </div>

    </template>

    其他组件基本与上面引入方法类似,不过也有区别,官网也有介绍,大部分组件都是以import { XXXX } from 'element-ui'的方式引入,然后以Vue.component(XXX.name, XXX);或者Vue.use(XXX)的方式注册,当然也有例外。

    例如:Message消息提示组件

    在main.js引入

    import { Message } from 'element-ui

    在main.js注册,这里是挂在在Vue原型上的

    Vue.prototype.$message = Message;

    使用

    <template>

      <div id="app">

            <el-button type="primary" @click='clickBtn'>主要按钮</el-button>

      </div>

    </template>

    <script>

    export default {

      name: 'App',

      components: {

      },

      methods:{

        clickBtn:function(){

          this.$message({

              message:'这是一条提示信息'

            });

        }

      }

    }

    </script>

    @-2.全局引入 当我们在项目使用ElementUI组件比较多时,就可以全局引入,方便省事儿

    引入

    在main.js中添加以下代码全局引入

    //引入elementui

    import ElementUI from 'element-ui'

    //样式需要单独引入

    import 'element-ui/lib/theme-chalk/index.css'

    //挂载

    Vue.use(ElementUI)

    使用

    <template>

      <div id="app">

            <el-button type="primary" @click='clickBtn'>主要按钮</el-button>

      </div>

    </template>

    相比按需引入,全局引入确实方便很多。

    关于element-ui的引用方法,可以参考element官网https://element.eleme.cn/#/zh-CN/component/i18nt,详细很好懂。

    相关文章

      网友评论

          本文标题:vue项目与element-ui结合使用

          本文链接:https://www.haomeiwen.com/subject/ihnwictx.html