Vue入门(1):render 和 template

162 阅读1分钟

vue 的版本

完整版

1、视图:从 HTML 或 template 得到视图,

2、文件名

  • 从 cdn 引入vue.js 或 vue.min.js;

  • webpack 引入:需要配置;

module.exports = {
  // ... 
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js' // 用 webpack 1 时需用 'vue/dist/vue.common.js' 
    } 
  } 
}
  • @vue/cli 引入:需要额外配置;

3、template:

//vue文件中的template标签
  <template>
      <div id="app">      
          {{n}}
          <button @click="add">+1</button>   
     </div> 
  </template>

//js中的template
new Vue({
   ...
    template : `
        <div id="app">      
          {{n}}
          <button @click="add">+1</button>   
        </div> 
    `
   ...
})

4、特点:有 compiler,体积比运行时大40%,直接写 html 标签,不需要写 h 函数;

运行时版

1、视图;写在 render 函数里,用 h 来创建标签;

2、文件名:

  • cdn 引入:vue.runtime.js;
  • webpack 默认使用此版;
  • @vue/cli 默认使用此版;

3、render写法:

//不完整版在js中构建视图
  render(h){ 
       return h('div', [this.n,h('{on:{click:this.add}’,'+1'])
   }


//不完整版使用vue-loader
//先创建一个demo.vue文件,在里面构建视图
    import demo from "./demo.vue"
     new Vue({
       el: "#app",
       render(h) {
         return h(demo)
       }
     })

4、特点:用户下载的 js 文件体积更小,但只支持 h 函数;

实践

1、使用非完整版,配合 vue-loader 和 vue 文件; 2、思路:

  • 保证用户体验:非完整版体积小,只支持 h 函数;
  • 保证开发体验:开发者可直接在 vue 文件里写 html 标签,而不写 h 函数;
  • vue-loader 将 vue 文件里的 html 转为 h 函数。

使用 codesandbox.io

1、网址:

CodeSandbox

2、Create Sandbox;

3、选择 vue ;

4、写好代码后可 export to zip 或将 url 复制。