Vue学习一 创建项目及项目总览

一、项目建创

vue create project-name

例如:

vue create hello-world

二、项目依赖下载

如果是网上下载的源码,需要这一步。如果是新建的项目默认已经下载了依赖。

yarn

三、项目运行

cd hello-world
yarn serve

四、VUE项目文件结构

image

五、main.js 文件说明:

import Vue from 'vue'   //引入Vue组件
import App from './App.vue'    //引入App组件

Vue.config.productionTip = false

new Vue({
//components: { App }  vue1.0的写法
  render: h => h(App),  // vue2.0的写法
  
}).$mount('#app')     //注册并mount组件

Vue2.0 render:h => h(App)
render函数是渲染一个视图,然后提供给el挂载,如果没有render那页面什么都不会出来
vue.2.0的渲染过程:

1.首先需要了解这是 es 6 的语法,表示 Vue 实例选项对象的 render 方法作为一个函数,接受传入的参数 h 函数,返回 h(App) 的函数调用结果。

2.其次,Vue 在创建 Vue 实例时,通过调用 render 方法来渲染实例的 DOM 树。

3.最后,Vue 在调用 render 方法时,会传入一个 createElement 函数作为参数,也就是这里的 h 的实参是 createElement 函数,然后 createElement 会以 APP 为参数进行调用,关于 createElement 函数的参数说明参见:Element-Arguments

结合一下官方文档的代码便可以很清晰的了解Vue2.0 render:h => h(App)的渲染过程。

[官方文档][1]:

1 render: function (createElement) {
2     return createElement(
3       'h' + this.level,   // tag name 标签名称
4       this.$slots.default // 子组件中的阵列
5     )
6   }

这里创建的vue实例没有el属性,而是在实例后面添加了一个$mount(’#app’)方法。

$mount(’#app’) :手动挂载到id为app的dom中的意思

当Vue实例没有el属性时,则该实例尚没有挂载到某个dom中;
假如需要延迟挂载,可以在之后手动调用vm.$mount()方法来挂载

需要注意的是:该方法是直接挂载到入口文件index.html 的 id=app 的dom 元素上的

六、组件结构

组件分三部分:

  1. 模板:Html结构。只能有一个根节点
  2. 行为:JS脚本
  3. 样式:CSS定义
<!-- 第一部分:模板 -->
<template>
  <div id="app">  <!-- 只能有一个根标签  所有的组组在这个标签下写-->
    <img alt="Vue logo" src="./assets/logo.png">
    <!--  调用组件 HelloWorld -->
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
  <!--加入多一个同级的根标签会出错。 -->
   <p>这里会出错</p>
</template>

<!-- 第二部分:行为 -->
<script>
<!-- 引入另外的组件HelloWorld -->
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld   //注册组件HelloWorld 。引入的组件要注册后才能使用
  }
}
</script>

<!-- 第三部分 样式-->
<!-- scoped ==关键字申明当前样式是局部样式。只影响当前组件。== -->
<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

scoped 关键字申明当前样式是局部样式。只影响当前组件。

多于一个根根签会报以下错误

Failed to compile.

./src/App.vue
Module Error (from ./node_modules/eslint-loader/index.js):

E:learnvue2hello-worldsrcApp.vue


  8:4  error  The template root requires exactly one element  vue/valid-template-root

✖ 1 problem (1 error, 0 warnings)

七、总结:执行过程

index.html -> main.js(引入vue,引用app.vue) ->App.vue(引入更多组件)

原文地址:https://www.cnblogs.com/KevinMO/p/14221419.html