草庐IT

javascript - Vue.js "npm run build"但 Vue.js 未绑定(bind)到 DOM/工作

coder 2025-03-13 原文

这里是 Vue.js 的新手。在 Mac OS 上使用版本:

$ npm --version
4.6.1
$ vue --version
2.8.1

我正在使用 webpack-simple init 和 vue-cli for vue 2.0。我在我的 Django 项目文件夹中为 vue 内容创建了一个名为 frontend 的文件夹。目录结构:

$ tree 
├── README.md
├── asnew
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── settings.py
│   ├── templates
│       └── index.html
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── frontend
│   ├── node_modules
│   ├── package.json
│   ├── src
│       ├── App.vue
│       ├── assets
│       ├── components
│       │   └── SearchPageResult.vue
│       ├── main.js
│       └── webpack.config.js
├── manage.py
├── media
├── requirements.txt
├── static
└── staticfiles

基本上在我的 index.html Django 模板中我有以下代码:

<script src="{% static 'js/vue/build.js' %}"></script>
<div id="app"></div>

渲染后,这将变成完整路径:

<script src="/static/js/vue/build.js"></script>

我使用 npm run build 创建并且我验证过它确实被浏览器加载/导入。我将 heroku CLI 作为开发服务器运行。

我是这样构建的:

$ cd frontend
$ npm run build

> vue-asnew@1.0.0 build /Users/me/MyProject/frontend
> cross-env NODE_ENV=production webpack --progress --hide-modules

Hash: d5e16854b8f88beea3e9
Version: webpack 2.4.1
Time: 4503ms
       Asset     Size  Chunks             Chunk Names
    build.js  87.4 kB       0  [emitted]  main
build.js.map   718 kB       0  [emitted]  main 

我不知道用 build.js.map 做什么,我不使用它。

但是,Vue 不起作用。虽然我在使用 npm run build 时没有遇到任何错误,但我在控制台中没有看到任何警告,我的指令(如 v-bind)都不起作用,我也无法访问我的对象 vm 来自 main.js:

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

# adding "export" in front here doesn't help either -
# in browser console it doesn't see `vm` object
const vm = new Vue({
    el: '#app',
    render: h => h(App)
});

作为控制台中的 vm(或只是 Vue!)。

> vm
VM1256:1 Uncaught ReferenceError: vm is not defined
> Vue
VM1256:1 Uncaught ReferenceError: Vue is not defined

我的 webpack.config.js 看起来像这样:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '../static/js/vue/'),
    publicPath: '/js/vue/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

npm run build 运行没有错误,所以我不确定发生了什么。

有什么想法吗?

最佳答案

npm run build 通常还会创建 index.html 文件,或者在您的情况下,它已经存在“webpack-simple”,其中它在关闭 body 标记之前包含 app.js 或 build.js。如果您在自己的 html 中包含 build.js,请尝试将其放在 <div id="app"></div> 之后在关闭 </body> 之前.

在底部包含脚本可确保首先加载实际页面内容;当最终下载脚本时,内容 (DOM) 将准备好供您的脚本操作。

此外,如果您:

const vm = new Vue({
    el: '#app',
    render: h => h(App)
});

您无法在控制台中访问“vm”。在 main.js 中创建的任何变量都不会全局可用。如果您需要它用于调试目的,您可以通过以下方式进行:

window.vm = new Vue({
  el: '#app',
  render: h => h(App)
});

然后您可以在控制台中访问“vm”。

关于javascript - Vue.js "npm run build"但 Vue.js 未绑定(bind)到 DOM/工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672702/

有关javascript - Vue.js "npm run build"但 Vue.js 未绑定(bind)到 DOM/工作的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  6. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  7. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  8. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  9. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  10. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

随机推荐