Vue(三)
第一个vue-cli项目
- vue-cli是官方提供的一个脚手架,用于快速生成一个vue的项目模板
环境配置
-
安装Node.js 官网下载地址,无脑下一步
-
在cmd中输入
node -v
和npm -v
进行测试 -
安装淘宝镜像加速器(cnpm),
npm install cnpm -g
- 安装过程有点慢,安装完后尽量少用
-
安装vue-cli,
cnpm install vue-cli -g
vue list
查看现有模板,测试是否安装成功
创建项目
新建项目
- 在项目目录下输入
vue init webpack myvue
新建项目- Project name:默认myvue
- Project description:直接回车
- Author:输入作者
- Vue build:选第一个Runtime + Compiler
- 下面一路选no
项目初始化(以管理员身份运行)
cd myvue
npm install
安装依赖环境- 按照提示输入
npm audit fix
npm rum dev
启动项目- 在IDEA中的Terminal运行,需要先以管理员身份运行IDEA
Ctrl+C
停止运行
Webpack
- Webpack是一个现代JavaScript应用程序的静态模块打包器(module bundler),当webpack处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个bundle
安装
-
npm install webpack -g
-
npm install webpack-cli -g
-
测试:
webpack -v
webpack-cli -v
使用
-
创建项目
-
创建一个名为modules的目录,用于放置js模块等资源文件
-
编写代码
-
hello.js
-
//暴露一个方法 exports.sayHi = function () { document.write("<h1>hello</h1>") }
-
main.js
-
var hello = require("./hello") hello.sayHi()
-
-
新键webpack.config.js
-
module.exports = { entry: './modules/main.js', output: { filename: "./js/bundle.js" } }
-
Terminal输入
webpack
进行打包 -
新键index.html导入打包后的js
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="dist/js/bundle.js"></script> </body> </html>
-
可以通过
webpack --watch
实现热部署
vue-router路由
安装
- 在当前项目下输入
npm install vue-router --save-dev
使用
-
导入并显式声明
-
import VueRouter from 'vue-router' Vue.use(VueRouter);
测试
-
写两个组件
-
content.vue
-
<template> <h1>内容页</h1> </template> <script> export default { name: "content" } </script> <style scoped> </style>
-
main.vue
-
<template> <h1>首页</h1> </template> <script> export default { name: "main" } </script> <style scoped> </style>
-
新键route目录,index.js,配置路由
-
import Vue from 'vue' import VueRouter from 'vue-router' import Content from '../components/content' import Main from '../components/main' //安装路由 Vue.use(VueRouter) //配置导出路由 export default new VueRouter({ routes: [ { //路由路径 path: '/content', //路由名字 name: 'content', //跳转的组件 component: Content }, { path: '/main', name: 'main', component: Main } ] });
-
在main.js中导入路由
-
import Vue from 'vue' import App from './App' import router from './router'//自动扫描里面的路由配置 Vue.config.productionTip = false new Vue({ el: '#app', //配置路由 router, components: { App }, template: '<App/>' })
-
在App.vue中进行路由测试
-
<template> <div id="app"> <h1>Vue-Router</h1> <router-link to="/main">首页</router-link> <router-link to="/content">内容页</router-link> <router-view></router-view> </div> </template> <script> import Content from './components/content' export default { name: 'App', components: { Content } } </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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。