基础环境

  1. 确保你有node.js环境
  2. 有Java JDK + Android SDK + AVD(安卓虚拟机)

安装Vue与Cordova

1
2
npm i -g vue-cli # 安装vue
npm i -g cordova # 安装cordova

快速开始

创建cordova项目

1
2
cordova create demo com.example.demo DEMO
cordova platform add android # 添加安卓平台
名称 必填 描述
demo 工程的文件夹名称
com.example.demo 应用程序的id,不填默认为io.cordova.hellocordova
DEMO APP 名称

在cordova项目中添加Vue项目

1
2
3
cd demo

vue init webpack vue-app
  1. 项目结构:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    drwxr-xr-x   - lianhaocheng 26 4 21:34 .
    .rwxr-xr-x 50 lianhaocheng 26 4 21:34 ├── build.sh
    .rw-r--r-- 934 lianhaocheng 26 4 20:48 ├── config.xml
    .rw-r--r-- 154 lianhaocheng 26 4 21:33 ├── Makefile
    drwxr-xr-x - lianhaocheng 26 4 20:48 ├── node_modules
    .rw-r--r-- 28k lianhaocheng 26 4 20:48 ├── package-lock.json
    .rw-r--r-- 619 lianhaocheng 26 4 20:48 ├── package.json
    drwxr-xr-x - lianhaocheng 26 4 20:48 ├── platforms
    drwxr-xr-x - lianhaocheng 26 4 20:48 ├── plugins
    drwxr-xr-x - lianhaocheng 26 4 20:57 ├── vue-app
    drwxr-xr-x - lianhaocheng 26 4 21:34 └── www
  1. vue-app/index.htmlhead中添加下面代码

    1
    2
    3
    4
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
  2. 修改vue-app/config/index.js中的build

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    build: {
    // Template for index.html
    index: path.resolve(__dirname, '../../www/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../../www'),
    assetsSubDirectory: './static',
    assetsPublicPath: './',
    ...
    }
  3. vue-app/index.htmlbody中添加

    1
    2
    3
    4
    5
    <body>
    <div id="app"></div>
    <script type="text/javascript" src="cordova.js"></script>
    <!-- built files will be auto injected -->
    </body>

打包或运行

  1. 打包vue项目

    1
    npm run build
  2. 打包安卓apk

    1
    cordova build android
  3. 不打包直接运行

    1
    cordova run android