V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
asanelder
V2EX  ›  问与答

vue 萌新求助,关于 template 的一个小问题

  •  
  •   asanelder · 2020-05-21 00:20:19 +08:00 · 936 次点击
    这是一个创建于 1435 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有如下两个文件

    index.html

    <html>
    	<head>
    		<title>Vue Hello World</title>
    	</head>
    	<body>
    		<div id="app"></div>
    	</body>
    </html>
    

    main.js

    import Vue from 'vue';
    
    new Vue({
    	el: '#app',
    	template: "<p> test <p>"
    });
    

    使用 webpack 打包后,在浏览器中运行,结果是这样的

    <html>
    	<head>
    		<title>Vue Hello World</title>
    	</head>
    
    	<body>
    		<div id="app"></div>
        	<script src="main.js"></script>
    	</body>
    </html>
    

    并没有替换到

    ,不明白啊,求大神指点!!!!
    12 条回复    2020-05-21 18:32:13 +08:00
    troycode
        1
    troycode  
       2020-05-21 08:42:48 +08:00
    页面里需引用 <template></template>
    SilentDepth
        2
    SilentDepth  
       2020-05-21 09:45:27 +08:00
    你的代码看起来没啥问题。控制台里没有异常吗?
    asanelder
        3
    asanelder  
    OP
       2020-05-21 10:53:31 +08:00
    @SilentDepth 没有任何异常,通过浏览器的 devtools 工具来查看的话,div element 没有了
    asanelder
        4
    asanelder  
    OP
       2020-05-21 10:56:47 +08:00
    @troycode 大神请明示啊,在哪里加呢。。。
    SilentDepth
        5
    SilentDepth  
       2020-05-21 11:30:27 +08:00
    我刚注意到你的 template 写错了,<p> 的关闭标签 = =|||
    asanelder
        6
    asanelder  
    OP
       2020-05-21 12:35:19 +08:00
    @SilentDepth 感谢回复啊,我找到原因了。

    主要是 webpack 最后打包成的 bundle.js 不包含 vue-compile, 所以 template: '<p> test </p>' 是不起作用的。

    要想起作用,需要使用 SFC 或者 render 函数。
    SilentDepth
        7
    SilentDepth  
       2020-05-21 12:39:16 +08:00
    不是啊,我试了下 <p>test</p> 是可以正常编译的
    asanelder
        8
    asanelder  
    OP
       2020-05-21 12:51:19 +08:00
    @SilentDepth 你的 webpack 文件? 你在浏览器中打开 html,显示 test 么?
    SilentDepth
        9
    SilentDepth  
       2020-05-21 14:28:53 +08:00
    本地又试了下,确实是不行(刚才在 CodeSandbox 上试的,可以正常编译)
    ghosthcp516
        10
    ghosthcp516  
       2020-05-21 15:22:33 +08:00
    vue.runtime.js 没有 template 编译相关的代码,不能直接写 template,vue.js 才行。
    ghosthcp516
        11
    ghosthcp516  
       2020-05-21 15:24:32 +08:00
    @ghosthcp516 即便使用了 vue-template-compiler, 也只能在.vue 文件中写 template, .js 文件就爱莫能助了
    asanelder
        12
    asanelder  
    OP
       2020-05-21 18:32:13 +08:00
    @ghosthcp516 差不多是这个意思,看我 6 楼的回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3485 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 11:22 · PVG 19:22 · LAX 04:22 · JFK 07:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.