vue(2.0)全家桶 总结及源码分析

Installation

Vue does not support IE8 and below

$ npm install vue

  • CLI
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack my-project
# install dependencies and go!
$ cd my-project
$ npm install
$ npm run dev

Runtime+Compiler vs. Runtime-only

// this requires the compiler
new Vue({
  template: `<div></div>`
})
// this does not
new Vue({
  render (h) {
    return h('div', this.hi)
  }
})

Development vs. Production Mode

开发/生产模式对于UMD构建是硬编码的:未缩小的文件用于开发,缩小的文件用于生产。 CommonJS和ES Module构建是针对捆绑包的,因此我们不为它们提供缩减版本。 你将负责自己最终捆绑。 CommonJS和ES Module构建还保存process.env.NODE_ENV的原始检查以确定它们应该运行的模式。 您应该使用适当的bundler配置来替换这些环境变量,以便控制Vue将运行的模式。替换process.env .NODE_ENV与字符串字面值也允许像UglifyJS这样的缩略器完全删除仅开发的代码块,减少最终文件大小。

//Using Webpack DefinePlugin
 var webpack = require('webpack')
 module.exports = {
   // ...
   plugins: [
     // ...
     new webpack.DefinePlugin({
       'process.env': {
         NODE_ENV: JSON.stringify('production')
       }
     })
   ]
 }

Introduction

What’s Vue.js:Vue is a progressive framework for building user interfaces.

Declarative Rendering 声明式渲染

//html
<div id="app">
  
</div>
//js
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

Conditionals and Loops

//html
<div id="app-3">
  <p v-if="seen">Now you see me</p>
</div>
<div id="app-4">
  <ol>
    <li v-for="todo in todos">
      
    </li>
  </ol>
</div>
//js
var app3 = new Vue({
  el: '#app-3',
  data: {
    seen: true
  }
});
var app4 = new Vue({
  el: '#app-4',
  data: {
    todos: [
      { text: 'Learn JavaScript' },
      { text: 'Learn Vue' },
      { text: 'Build something awesome' }
    ]
  }
})

Handling User Input

To let users interact with your app, we can use the v-on directive to attach event listeners that invoke methods on our Vue instances:

<div id="app-5">
  <p></p>
  <button v-on:click="reverseMessage">Reverse Message</button>
</div>
<div id="app-6">
  <p></p>
  <input v-model="message">
</div>
//js
var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
});
var app6 = new Vue({
  el: '#app-6',
  data: {
    message: 'Hello Vue!'
  }
});

Composing with Components

//js
// Define a new component called todo-item
Vue.component('todo-item', {
  template: '<li>This is a todo</li>'
})
//html
<ol>
  <!-- Create an instance of the todo-item component -->
  <todo-item></todo-item>
</ol>

Relation to Custom Elements—区别

  1. Web Components Spec 一直是草案,而Vue components 不依赖任何处理可以工作在任何浏览器(IE9以上) 且可嵌入到原生element。
  2. Vue组件提供了在纯自定义元素中不可用的重要功能,最突出的是跨组件数据流,自定义事件通信和构建工具集成。

The Vue Instance

Constructor

Although not strictly associated with the MVVM pattern, Vue’s design was partly inspired by it.

var data = { a: 1 }
var vm = new Vue({
  el: '#example',
  data: data
})
vm.$data === data // -> true
vm.$el === document.getElementById('example') // -> true
// $watch is an instance method
vm.$watch('a', function (newVal, oldVal) {
  // this callback will be called when `vm.a` changes
})

Instance Lifecycle Hooks

![http://vuejs.org/images/lifecycle.png][http://vuejs.org/images/lifecycle.png]

Template Syntax

Vue.js uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers. Under the hood, Vue compiles the templates into Virtual DOM render functions(虚拟DOM渲染函数). Combined with the reactivity system, Vue is able to intelligently figure out the minimal amount of components to re-render and apply the minimal amount of DOM manipulations when the app state changes.

Interpolations(插值)

  • Text:<span>Message: </span>
  • Raw HTML:<div v-html="rawHtml"></div>
  • Attributes:<div v-bind:id="dynamicId"></div>
  • Using JS Expressions:<div v-bind:id="'list-' + id"></div>

Directions—Directives are special attributes with the v- prefix.

  • Arguments:Some directives can take an “argument”, denoted by a colon after the directive name. <a v-on:click="doSomething">
  • Modifiers: indicate that a directive should be bound in some special way. <form v-on:submit.prevent="onSubmit"></form>
  • Filters: apply common text formatting.

Vue 2.x过滤器只能在胡子插值和v绑定表达式(后者自2.1.0以来支持)内使用,因为过滤器主要设计用于文本转换目的。 对于其他指令中更复杂的数据变换,应该使用计算属性。

 //html
 
 //js
 new Vue({
   // ...
   filters: {
     capitalize: function (value) {
       if (!value) return ''
       value = value.toString()
       return value.charAt(0).toUpperCase() + value.slice(1)
     }
   }
 })
  • Shorthands:
 <!-- full syntax -->
 <a v-bind:href="url"></a>
 <!-- shorthand -->
 <a :href="url"></a>
 <!-- full syntax -->
 <a v-on:click="doSomething"></a>
 <!-- shorthand -->
 <a @click="doSomething"></a>

Computed Properties and Watchers

Computed Properties

 computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
  • Computed Caching vs Methods: the computed properties are cached based on their dependencies
  • Computed vs Watched Property:better to use a computed property
  • Computed Setter:you can provide a setter when you need it:

Watchers

when you want to perform asynchronous or expensive operations in response to changing data.

Class and Style Bindings

Binding HTML Classes

  • Object Syntax ```
- Array Syntax

``` - With Components ``` //When isActive is truthy, the rendered HTML will be:

Hi

``` ### Binding Inline Styles - Object Syntax/Array Syntax ```
``` - Auto-prefixing:Vue已替你考虑CSS的浏览器兼容性 ## List Rending ### v-if/v-else-if ```
A
B
C
Not A/B/C
``` - Controlling Reusable Elements with key ``` ``` - v-show ```

Hello!

``` - v-if vs v-show v-if is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles. v-if is also lazy: if the condition is false on initial render, it will not do anything - the conditional block won’t be rendered until the condition becomes true for the first time. In comparison, v-show is much simpler - the element is always rendered regardless of initial condition, with just simple CSS-based toggling.And Please note that v-show doesn’t support the ```

Tags:

Categories:

Updated:

Leave a Comment

comments powered by Disqus