结合webpack使用vue-router
demo结构
webpack.config.js
var path = require('path'); // const { VueLoaderPlugin } = require('vue-loader'); // 通过node的模块操作,向外暴露一个配置对象 module.exports = { entry: path.join(__dirname, './src/main.js'), // 入口,表示要使用webpack打包哪个文件 output: { // 出口 path: path.join(__dirname, './dist'), filename: 'bundle.js' }, module: { //用于配置所有第三方模块加载器 rules: [ //所有第三方模块的匹配规则 // 首先安装loader: npm i style-loader css-loader -D, 然后配置 { test:/\.css$/, use: ['style-loader','css-loader'] }, // 首先安装loader: npm i url-loader file-loader -D, 然后配置 { test:/\.(jpg|png|gif|bmp|jpeg)$/, use: ['url-loader'] // limit单位byte,如果图片大于等于limit给定值,则不会被转为base64格式字符串 // name=[name].[ext]:打包的图片原名相同 // use: ['url-loader?limit=1000&name=[name].[ext]'] }, // 首先安装loader: npm i vue-loader vue-template-compiler -D, 然后配置 { test: /\.vue$/, use: 'vue-loader' } ] }, plugins: [ // new VueLoaderPlugin() ], };
package.json
{ "name": "webpack-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "vue": "^2.5.2", "vue-router": "^3.0.1" }, "devDependencies": { "css-loader": "^0.28.0", "file-loader": "^1.1.4", "style-loader": "^0.21.0", "url-loader": "^1.0.1", "vue-loader": "^13.3.0", "vue-template-compiler": "^2.5.2", "webpack": "^3.6.0" } }
main.js
// 这是项目的入口js文件 // import $ from 'jquery'; import './css/common.css'; // 注意:在webpack中,使用下面这句导入vue,功能不完整,只提供runtime-only的方式,并没没有提供向网页中那样的使用方式 // import Vue from 'vue'; // 导入完整的vue import Vue from '../node_modules/vue/dist/vue.js'; import VueRouter from 'vue-router'; Vue.use(VueRouter); // 导入App组件 import App from './App.vue'; // 默认webpack无法处理.vue文件,第一步安装第三方loader: npm i vue-loader vue-template-compiler -D // 第二步:webpack.config.js配置 { test: /\.vue$/, use: 'vue-loader' } import account from './components/account.vue'; import goodslist from './components/goodslist.vue'; var router = new VueRouter({ routes: [ {path: '/account', component: account}, {path: '/goodslist', component: goodslist} ] }); var vm = new Vue({ el: '#app', data: { msg: 'hello vue' }, // render:将App组件渲染到el指定的div#app中(div#app中其他内容被覆盖) render: c => c(App), router });
index.html
<!DOCTYPE html> <html> <head> <title>标题</title> <meta charset="utf-8"> </head> <body> <div id="app"></div> <script type="text/javascript" src="../dist/bundle.js"></script> </body> </html>
App.vue
<template> <div> <h1>App组件</h1> <router-link to="/account">Account</router-link> <router-link to="/goodslist">GoodsList</router-link> <router-view></router-view> </div> </template> <script></script> <style></style>
posted on 2019-07-27 13:34 wenbin_ouyang 阅读(377) 评论(0) 编辑 收藏 举报