【问题标题】:Vue js in cordova科尔多瓦中的 Vue js
【发布时间】:2017-05-14 22:05:02
【问题描述】:

我正在努力在 Cordova 中实现一个简单的 Vue.js 应用程序。一切正常,除了我不知道如何将科尔多瓦事件(设备就绪,暂停,...)拦截到我的 vue 应用程序中。我使用了来自 vue-cli 的 Webpack 模板。

这是我的文件js/index.js

const app = {
  initialize: function () {
    console.log('initialize')
    this.bindEvents()
  },
  bindEvents: function () {
    document.addEventListener('deviceready', this.onDeviceReady, false)
  },
  onDeviceReady: function () {
    app.receivedEvent('deviceready')
  },
  receivedEvent: function (id) {
    console.log('Received Event: ' + id)
  }
}

app.initialize()

src/main.js

import Vue from 'vue'
import App from './App'

/* eslint-disable no-new */
const app = new Vue({
  template: '<App/>',
  components: { App }
})

app.$mount('#app')

配置/index.js:

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    //assetsPublicPath: '/',
    productionSourceMap: true,
    productionGzip: false,
    productionGzipExtensions: ['js', 'css']
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},
    cssSourceMap: false
  }
}

webpack.base.conf.js:

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  resolve: {
    extensions: ['', '.js', '.vue', '.json'],
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'vue$': 'vue/dist/vue.common.js',
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'semantic': path.resolve(__dirname, '../node_modules/semantic-ui-css/semantic.min.js')
    }
  },
  resolveLoader: {
    fallback: [path.join(__dirname, '../node_modules')]
  },
  plugins: [
    new webpack.ProvidePlugin({
        // jquery
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        semantic: 'semantic-ui-css',
        'semantic-ui': 'semantic-ui-css'
    })
  ],
  module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  eslint: {
    formatter: require('eslint-friendly-formatter')
  },
  vue: {
    loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
    postcss: [
      require('autoprefixer')({
        browsers: ['last 2 versions']
      })
    ]
  }
}

webpack.prod.conf:

var webpackConfig = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  vue: {
    loaders: utils.cssLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    })
  ]
})

if (config.build.productionGzip) {
  var CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

这是我的项目结构:

我应该怎么做才能从 Cordova 获取事件到我的 Vue 组件?

【问题讨论】:

  • 您收到什么错误?这两个“应用”变量是否相互冲突?
  • 我没有收到任何错误,但我没有收到devicereadyevents。我认为我应该做的是,当我收到事件deviceready 时,我实例化了我的 Vue 应用程序,但该事件永远不会触发
  • index.js还是main.js先加载到页面中?您是在物理设备上还是在浏览器中运行它(您需要设备上的cordova 编译过程来包含cordova.js)。尝试移动您的科尔多瓦初始化代码,如果您知道这一点,则尝试移动 IDK,但您的科尔多瓦初始化代码现在仅打印到控制台(不初始化 Vue)。此外,一般来说,将所有内容命名为 app/index/main 是一个坏主意。
  • 我的 Webpack 条目是 './src/main.js'。我主要在浏览器中运行它,并不时在物理 android 设备上对其进行测试。我知道科尔多瓦初始化代码不会实例化我的 vue 应用程序,但我无法从科尔多瓦捕获任何事件
  • 是的,cordova 事件不会在浏览器中触发。最近在设备上尝试过?

标签: javascript cordova vue.js


【解决方案1】:

看到这篇文章,它对我有用:

https://coligo.io/building-a-mobile-app-with-cordova-vuejs/

为了允许应用访问 Vue.js 库,我们还需要在 www/index.html 的 Content Security Policy (CSP) 元标记末尾添加以下内容:

; script-src 'self' http://cdn.jsdelivr.net/vue/1.0.16/vue.js 'unsafe-eval'

【讨论】:

    【解决方案2】:

    看起来问题是 Cordova.js 未包含在浏览器中,您需要在物理设备上进行测试。

    但这并不意味着您不能在浏览器中进行原型设计。在 JS 中,window.cordova 将在 cordova 已加载时被定义。所以你可以像这样设置你的初始化

    if(window.cordova){
      //add deviceready event to start app
    } else {
      //call starting function
    }
    

    对于需要物理设备的东西:振动、加速度计等,你必须构建并部署到设备上,浏览器本身是不够的。

    【讨论】:

    • 似乎在构建时没有加载cordova(chrome远程devtools告诉我没有设置window.cordova),添加了webpack配置问题,因为它可能是相关的
    • window.cordova 将在设备上定义,其中cordova 构建过程包括cordova.js 文件。它将在缺少cordova.js 的浏览器中未定义。您可以检查它是否已定义并为每个实例创建编程路径,如果已定义则等待 deviceready,如果未定义则等待 document ready。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 2017-10-29
    • 2013-12-02
    相关资源
    最近更新 更多