javascript - 将 Vue 添加到现有的旧网站,删除 div 而不是显示旧的 html

标签 javascript vue.js

我试图用 Vue 包装我的旧网站,所以所有旧的 jQuery 脚本应该仍然运行并且所有旧的 HTML 应该显示,但是由于某种原因 el 和它里面的所有东西都被删除了.

这是在使用脚本的 webpacked 版本时,例如:

<html>
    <head></head>
    <body>
        <div id="wrapper">
            <p>dsadfasfasfasfas</p>
            <p>dfasdsadasdasdas</p>
        </div>
    </body>
    <script src="/assets/js/app.min.js"></script>
</html>

不会在 body 标签中显示任何内容。但是,如果我在网站顶部导入 Vue,并将下面的代码放在 webpacked 版本的位置,它就可以正常工作!

window.app = new Vue({
    el: '#wrapper',
    data: {
        test: 'hello world'
    },
    created() {
        console.log('Vue Running');
    }
});

编辑

这也是被编译的 app.js:

import Vue from 'vue';

// window.EventBus = new Vue();
window.app = new Vue({
    el: '#wrapper',
    data: {
        test: 'hello world'
    },
    created() {
        console.log('Vue Running');
    }
});

编辑

这是我的 webpack.config.js:

const path = require('path');
module.exports = {
    mode: 'production',
    entry: [
        './resources/js/vue/app.js'
    ],
    output: {
        filename: 'app.min.js',
        path: path.resolve(__dirname, 'public_html/assets/js/vue')
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: 'vue-loader'
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin()
    ]
};

编辑2

刚刚删除了 import vue from 'vue',并使用正常的 script src=... 方式导入它,它就可以工作了。我的印象是,如果我导入 vue 并编译,那么这会在我的网站中包含 vue 吗?

最佳答案

那是因为你的 Webpack 配置不完整。

如果你打开浏览器控制台,你会看到:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

#wrapper 中的 html 是一个模板,但 Vue 无法编译(和使用它),因为您的构建包含仅运行时版本的 Vue。

只需将此添加到 webpack.config.js:

resolve: {
  alias: {
    'vue$': 'vue/dist/vue.esm.js'
  },
},

这将包括 Vue 的运行时+编译器构建。

关于javascript - 将 Vue 添加到现有的旧网站,删除 div 而不是显示旧的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831488/

相关文章:

jquery - Vue.js与jQuery datepicker/timepicker双向绑定(bind)

vue.js - 如何仅在某些 Vue.js 组件上显示导航栏元素?

javascript - 如何使用 VueJS 防止数字输入

Javascript 在鼠标单击时触发按键而不使用 Jquery

javascript - Firebase 的云功能 : completing long processes without touching maximum timeout

javascript - 将对象设置为拆分数组

javascript - 我如何在 axios 拦截器中重定向?

javascript - knockout : manually update an observable via code?

javascript - 如何使用 ReactJS 监听 iframe keydown 事件

javascript - Vue - 观察 this.$el.clientWidth 的变化