鍍金池/ 問(wèn)答/HTML/ vue webpack 練習(xí)

vue webpack 練習(xí)

1.npm init -y
2.npm install --save-dev webpack
3.npm install vue

4.src/index.js

import Vue from 'vue'

Vue.component('todo-item', {
  props: ['todo'],
  template: '<li>{{ todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [{
        id: 0,
        text: '蔬菜'
      },
      {
        id: 1,
        text: '奶酪'
      },
      {
        id: 2,
        text: '隨便其它什么人吃的東西'
      }
    ]
  }
})

5.dist/index.html

<body>
  <div id="app-7">
    <ol>
      <todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id">
      </todo-item>
    </ol>
  </div>
  <script src="bundle.js"></script>
</body>

6.npx webpack src/index.js dist/bundle.js

打開(kāi)index.html報(bào)錯(cuò)
bundle.js:894 [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.

請(qǐng)問(wèn)是什么原因啊,應(yīng)該如何修改

回答
編輯回答
墨小羽

問(wèn)題是你使用了 runtime-only 的編譯方式,這個(gè)編譯方式是不包含模板編譯器的,因此所有的元素都是預(yù)編譯完成 的標(biāo)準(zhǔn) html 元素。
而你在 html 頁(yè)面中使用了 vue 組件,自然就不能被識(shí)別,vue 捕獲了這一問(wèn)題并告知你。

  • 解決方案是:
    將你要使用的 vue 組件模板寫(xiě)入 vue 的 render 方法中去,或者用 compiler-included
    編譯方式將模板編譯器編入bundle.js,用于解析 vue 元素。

完整的 vue 框架其實(shí)包含了模板編譯器和運(yùn)行時(shí)控制器兩部分,compiler-included 編譯方式是將兩者都編譯到 bundle.js,runtime-only 方式則是只編譯運(yùn)行時(shí)控制器到 bundle.js。

  • compiler-included 編譯方式生產(chǎn)的 vue 腳本工作原理是:

    1. 內(nèi)置的template compiler先將頁(yè)面上的元素進(jìn)行收集(此時(shí)頁(yè)面不加載)
    2. 分析其中的元素,找出 vue 組件,將它們編譯成 html 元素,并綁定上相應(yīng)的事件
    3. 將解析完成的組件渲染(render)到頁(yè)面上
    4. vue 控制器在運(yùn)行時(shí)(runtime)中持續(xù)服務(wù)
  • runtime-only 編譯方式的原理:

    1. 先用模板編譯器進(jìn)行一次預(yù)編譯,把代碼中的 vue 組件全部渲染成 html 元素,這樣就省略了 compiler-included 方式的 1 和 2
    2. 將組件直接渲染
    3. vue 控制器在運(yùn)行時(shí)持續(xù)服務(wù)
2017年2月17日 17:59