模块化开发: 创建Element应用
来自CloudWiki
目录
创建项目
参考使用Hbuilder 创建Vue应用创建项目
安装Node.js
因为安装Element包需要npm 安装工具,
而后者是Node.js自带的,所以我们首先需要安装Node.js
安装方法参见:Windows 安装Node.js
安装Element
打开Windows命令提示符窗口,
切换到项目所在目录(如我的项目叫Hello123-2:
d: cd D:\cloud\2022\Tech\element-ui\Hello123-2
执行 npm i element-ui -S
安装完成之后,会在node_modules目录下看到element-ui的包
也会在package.json中看到element-ui的有关应用:
{ "name": "default", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build" }, "dependencies": { "core-js": "^2.6.5", "element-ui": "^2.15.9", "vue": "^2.6.10" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.8.0", "@vue/cli-service": "^3.8.0", "vue-template-compiler": "^2.6.10" } }
编写代码
目录结构
以下内容参考第一个Element UI程序的代码进行了改写,
代码基本类似,只不过应用工程化思维把他们分拆了一下。
public/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>default</title> </head> <body> <noscript> <strong>We're sorry but default doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
APP.vue
App.vue: 项目入口文件
将下述内容覆盖至app.vue原有内容。
下述内容主要分为三部分,html模板,scrpit代码, css代码,
这一个文件相当于创建了一个vue模块,并通过export default输出,以供其他文件使用。
export default作用可参考: vue中的export default
<template> <div id="app"> <el-button @click="onTouch">Button</el-button> <el-dialog :visible.sync="visible" title="Hello world"> <p>你好,这是一个button按钮哦~</p> </el-dialog> </div> </template> <script> export default { name: 'app', data() { return { visible: false } }, methods: { onTouch() { console.log('submit!'); this.visible = true; } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
main.js
main.js: 项目的核心文件。
这里由它来创建实例,绑定页面节点。
render函数可参考:vue中的render函数
这里主要是添加了这么几行,引用了Elment UI:
import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);
具体代码:
import Vue from 'vue' import App from './App.vue' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')
运行项目
浏览器打 开地址localhost:8080
如果一一切正常,会看到画面中间出现经典的ELement按钮,一点击会有如下弹窗。