Vue脚手架

Vue脚手架

1. 安装Vue CLI

Vue CLI是Command-Line Interface, 翻译为命令行界面, 但是俗称脚手架。

Vue CLI使用前提是安装了 nodeJs 和 Webpack 。

npm install -g @vue/cli

以上命令安装的是Vue CLI3+ 的版本,如果想按照Vue CLI2的方式初始化项目,则需使用如下命令安装一个桥接工具。

npm install -g @vue/cli-init

Vue CLI2 初始化项目命令:

vue init webpack 项目名

Vue CLI3 初始化项目命令:

vue create 项目名

2. Runtime-Compiler和Runtime-only

Runtime + Compiler: 运行时+编译器

Runtime-only: 仅限运行时

// main.js
new vue({
  template: '<div><{{ message}}/div>'
})

上面代码这种情况就需要编译器:compiler

下面代码这种情况则不需要compiler,可直接使用只含有运行时的构建版本runtime-only

// main.js
new vue({
  render(h){
    return h('div',this.message)
  }
})

render和template

为什么带有 template 的需要 comliler,而带有 render 函数则不需要?

我们需要先理解Vue应用程序是如何运行起来的

img

vue会把 template 放在 vue 实例的vm.options 中,然后把template 解析成ast( 抽象语法树:abstract syntax tree ),再把 ast 编译成 render 函数。render函数会把 template 最终翻译成虚拟DOM树 Virtual dom,然后把虚拟DOM树渲染成真实DOM。

所以,在如下代码中,当把template给传给vue实例后,会经过这样的步骤:

template –> ast –> render –> virtual dom –> ui

new vue({
  template: '<div><{{ message}}/div>'
})

而Runtime-only则经过这样的步骤:render –> virtual dom –> ui,如下代码:

new vue({
  render(h){
    return h('div',this.message)
  }
})

由此可见,Runtime-only 不用经过 template –> ast –> render 步骤,可vue开发中,vue组件中含有大量的 template ,那么这些template 难道不需要 template –> ast –> render 这一步骤吗?

是的,vue 组件中的template 是不需要template –> ast –> render这一步骤的,因为这些组件中的template 最终被编译出来的就是普通的对象,而这一普通的对象中,已经将template 全部渲染成render函数了,那么这些 .vue 组件中的template 是有谁处理的呢?

是由 vue-template-compiler 解析的。要想执行 .vue 文件的代码,需要安装开发时依赖 vue-loader 和 vue-template-compiler 。而在 Vue CLI 中,webpack 已经帮我们安装好了这些东西。正是由于 vue-template-compiler,所以vue 组件中的template 是不需要 Runtime-compiler 的。

由此可见,使用Runtime-only 有两点好处:1,性能更高;2,代码量更少

简单总结:

如果在之后的开发中,依然使用template,就需要选择Runtime-Compiler

如果在之后的开发中,使用的是.vue文件夹开发,那么可以选择Runtime-only

3. render函数的使用

new Vue({
  render: function(createElement){
    // createElement('标签',{标签的属性},['标签中的内容',....])
    return createElement('h2',{class:'center'},['hello world'])
  }
}).$mount('#app')

funtion函数中传入一个参数,该参数是一个函数,这个函数可以随意取名,它的作用是创建标签,render 函数会将return 的标签挂载到 #app 中,在createElement 的第三个参数中,可以嵌套createElement 函数来创建子标签。如下。

new Vue({
  render: function(createElement){
    return createElement('h2',
    {class:'center'},
    ['hello world',createElement('button',['按钮'])])
  }
}).$mount('#app')

这是render函数的普通用法,createElement 还可以传入组件

new Vue({
  render: function(createElement){
    return createElement(App)
  }}).$mount('#app')

因为funtion中的参数名字可以随便取,用箭头函数最终还可以简写成这样

new Vue({
  render: h => h(App),
}).$mount('#app')

4. 配置去哪了

t(App)
}}).$mount(’#app’)




因为funtion中的参数名字可以随便取,用箭头函数最终还可以简写成这样

```js
new Vue({
  render: h => h(App),
}).$mount('#app')

4. 配置去哪了

在 node_modules – @vue – cli-service – lib

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值