Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue教程13:基于Webpack构建项目 #14

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Vue教程13:基于Webpack构建项目 #14

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

代码示例:/lesson13/

创建Vue项目的文件夹结构

├── package.json
├── webpack.config.js # Webpack配置文件
├── index.html # 项目HTML文件
├── css # 项目样式文件夹
├── dest # 项目打包后输出文件夹
├── src # 项目开发文件夹
│ ├── vm.js # 项目入口文件
│ ├── router.js # 路由配置文件
│ ├── components # 组件文件夹

Webpack基本配置

const path=require('path');

module.exports={
  mode: 'development',  // 开发模式
  entry: './src/vm.js', // 入口文件配置
  output: {
    path: path.resolve(__dirname, 'dest'),  // 输出文件夹
    filename: 'bundle.min.js' // 打包输出的文件名
  },
  module: {
    rules: [
      { // 处理CSS
        test: /\.css$/i, 
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

HTML文件

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
      <!-- name属性的值对应路由配置中components中的属性名 -->
      <router-view name="header"></router-view>
      <!-- 渲染默认视图 -->
      <router-view></router-view>
    </div>
  </body>
  <!-- 引用打包后的js文件 -->
  <script src="dest/bundle.min.js" charset="utf-8"></script>
</html>

入口js文件vm.js

// 引入Vue的es module模块,使用vue-cli时,因为配置了alias,所以可以直接引用vue
import Vue from 'vue/dist/vue.esm';
// 引入VueRouter模块
import VueRouter from 'vue-router';

// 引入路由配置
import router from './router';

// 引入项目样式表
import '../css/main.css';

// 安装VueRouter插件
Vue.use(VueRouter);

// 配置Vue应用
const vm=new Vue({
  el: '#app',
  data: {},
  router
});

路由配置router.js

// 引入VueRouter模块
import VueRouter from 'vue-router';

// 引入组件
import Header from './components/header';
import Home from './components/home';
import News from './components/news1';

export default new VueRouter({
  routes: [
    {
      path: '/index', // 路由的路径
      name: 'index',  // 路由名称,可选属性,定义后可以用其实现跳转
      components: { // 通过components属性显示多个组件
        header: Header,  // 命名视图,对应<router-view name="header"></router-view>
        default: Home  // 默认视图,对应<router-view></router-view>
      }
    },
    {
      path: '/news',
      name: 'news',
      components: {
        header: Header,
        default: News
      }
    }
  ]
})

编译项目

在命令行使用webpack命令就可以进行编译,在浏览器中打开index.html就可以查看效果。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant