webpack+vue2.0项目 (二)热加载,vue-router
目录创建好之后,命令行输入
npm run dev
因为在配置文件config/index.js里:
dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false }
webpack会默认创建本地服务器监听8080端口,autoOpenBrowser为true,浏览器会自动打开,我一般会关掉,因为以后调试会运行很多次 npm run dev;
然后打开
下面看下几个主要的文件:
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>hello</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
index里面只有一个id为app的div,因为webpack会自动将js,css添加进去;
main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })
这个文件,首先将vue,App(引入的component),router(配置路由);
创建Vue实例然后将App组件以<App><App/>的方式放入index里id为app的元素里;
然后是App.vue
<template> <div id="app"> <img src="./assets/logo.png"> <router-view></router-view> </div> </template> <script> export default { name: 'app' } </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>
对vue组件不熟的可以去看官方文档,真的很详细;
在template中引入了 <router-view></router-view> 这代表路由,我们可以看下路由的配置;
router.js
import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello } ] })
这个官方文档讲得也很清楚,path写的是路径,这个文件的意思是当路径是"/"(即当前页面)时,引入组件Hello.vue;
对应App.vue就是打开首页的同时要引入Hello.vue;
当然在真正的项目中会有多个路由,只要在routes中多加介个配置就行了;
下面是我在项目中的router.js文件,注:引入组件文件的时候,一定要注册组件
import Vue from 'vue' import Router from 'vue-router' import goods from '../components/goods/goods' import seller from '../components/seller/seller' import ratings from '../components/ratings/ratings' Vue.use(Router) export default new Router({ linkActiveClass:'active', routes: [ { path: '/goods', component: goods }, { path: '/seller', component: seller }, { path: '/ratings', component: ratings }, { path: '/', component: goods }, ] })
linkActiveClasss:当路由切换到当页时会自动给顶层元素分配一个class属性,可以去自定义它,如下:
另外webpack最大的优点之一就是他的热加载:当你修改文件后(除配置文件),webpack会自动编译,并刷新页面
如果出现错误会在上面显示,如果正常会显示如下: