Learn the vue.js of the Web from scratch (i) Vue.js overview, basic structure, directives, event modifiers, styles

Source: Internet
Author: User
Tags modifiers

Hello everyone, here is "learn the Web series from scratch" and synchronize updates at the following address ...

  • Github:github.com/daotin/web
  • Public number: The top of the Web front
  • Blog Park: http://www.cnblogs.com/lvonve/
  • csdn:blog.csdn.net/lvonve/

Here I will start with the Web front End 0 Foundation, step-up learning web-related knowledge points, during the period will also share some fun projects. Now let's go to the Web Front end learning Adventure tour!

I. Vue.js Overview 1, what is Vue.js

Vue.js is currently the hottest front-end frame, react is the most popular one front-end framework (react in addition to developing Web sites, but also to develop mobile apps, Vue syntax can also be used for mobile app development, need to rely on Weex)

Vue.js is one of the front-end mainstream framework , and Angular.js, react.js together, and become the front-end three main mainstream framework!

Vue.js is a framework for building user interfaces, focusing only on the view layer , which is easy to use and easy to integrate with third-party libraries or existing projects. (Vue has a matching third-party library that can be integrated for large-scale project development).

In Vue, a core concept is to let users no longer manipulate DOM elements, freeing up the user's hands, so that programmers can more time to focus on business logic;

2. The difference between frame and library

Framework : is a complete set of solutions, the project is more intrusive, if the project needs to replace the framework, you need to re-architect the entire project.

Library (plug-in): Provide a small function, the project is less intrusive, if a library can not complete some requirements, it is easy to switch to other libraries to implement the requirements. (e.g. switch from jQuery to Zepto, etc.)

3. MVC and MVVM differences and linkages

MVC is the back-end layered development concept;

M is the data layer, the V view layer, and the C logic layer.

MVVM is the concept of the front-end view layer, focusing on the separation of view layers, that is to say: MVVM puts the front-end view layer into three-part Model, view, VM ViewModel.

The VM is the middle layer, responsible for the coordination of the V Layer and M layer, the V layer is the view layer (corresponding to the DOM element), is our web page HTML structure, the M layer is the data inside the page (corresponding to the JavaScript object).

Diagram of the contact for MVC and MVVM:

II. Basic structure of vue.js

The basic structure of the vue.js is divided into three main blocks:

1, import the Vue package;

2. Set an area (element) controlled by Vue in the body;

3, in script new A Vue instance, the parameter is an object, the object generally has three elements el , datamethods

The EL is associated with the ID or class name of the element in the body that is controlled by Vue.

Data is stored on the page;

Methods is a collection of page event objects.

Example:

 <! DOCTYPE html>

{{msg}}: Data can be used directly in HTML in the form of double-curly braces .

Three, Vue instruction 1, interpolation expression

An interpolated expression is inserted into the HTML code in a similar form as a double-brace {{ msg }} .

2, V-cloak

{{ msg }}when inserting data in the same way, if the network speed is very slow, the {{ msg }} value represented will not be displayed immediately, but will display the {{msg}} The string itself, how to solve the problem?

With V-cloak and CSS expressions, you can solve the problem of blinking an interpolated expression so that the string itself is not displayed when the network is not finished loading.

Example:

<style>  [v-cloak] {    display: none;  }</style>...<p v-cloak> {{ msg }} </p>
3, V-text

The default v-text is no flicker problem, but V-text overrides the original content in the element, and V-cloak replaces only the interpolated expression, not emptying the contents of the entire element.

<span v-text="msg"></span>
4, v-html

V-text Knowledge inserts the plain text format content, and v-html can be inserted into the HTML tag code and parsed out.

<span v-html="msg"></span>...data: {  msg: '
5, V-bind

V-bind is the instruction provided in Vue for binding properties .

Note: v-bind: instructions can be abbreviated to:

<input type="button" value="按钮" v-bind:title="mytitle + '123'">...data: {  mytitle: '这是一个自己定义的title'},

The content inside the title is not a string, but instead it replaces the variable in data to get a whole string.

6, V-on

V-on is the event binding mechanism in Vue.

Note: v-on: instructions can be abbreviated to@

<input type="button" value="按钮" :title="mytitle + '123'" v-on:click="show">...data: {  mytitle: '这是一个自己定义的title'},methods: { // 这个 methods属性中定义了当前Vue实例所有可用的方法  show: function () {    alert('Hello')  }}

The Show method in methods is automatically called when the button is clicked.

Case: Font scrolling playback
<! DOCTYPE html>

Attention:

1. In a VM object instance, if you want to get data on it, or if you want to invoke a method in methods, you have to pass or access it, and this.数据属性名 this.方法名 here This is the VM instance object that we are new.

2, the VM instance, will automatically listen to their own data in all the changes, as long as the data changes, the latest data will be automatically synchronized to the page; "Good: programmers only need to care about the data, do not need to consider how to re-render the DOM page"

7, V-model

V-bind can only implement one-way binding of data, from M automatically bound to V (that is , data modification, automatic synchronization to HTML), can not achieve two-way data binding.

Using the V-model directive, you can implement two-way data binding of the form elements and the data in the model ( not only the data can be modified, automatically synced to the HTML, but also the code of the HTML can be modified to synchronize to data).

Note: V-model can only be used in table cells .

Example:

<input type="text" style="width:100%;" v-model="msg">...data: {    msg: 'hello vue.'},
Case: A simple calculator
<!     DOCTYPE html>
8, V-for

8.1. V-for Loop Normal Array

If we want to loop assignment to P tag data in list=[1,2,3,4,5,6]; Array of words, this will write:

<body>    <div id="app">        <p>{{list[0]}}</p>        <p>{{list[1]}}</p>        <p>{{list[2]}}</p>        <p>{{list[3]}}</p>        <p>{{list[4]}}</p>    </div>    <script>        var vm = new Vue({            el: '#app',            data: {                list: [1, 2, 3, 4, 5, 6]            },            methods: {}        });    </script></body>

In this case, it will be very cumbersome. Instead, V-for provides a loop through the list array to assign a value to the P tag. As follows:

<body>    <div id="app">        <p v-for="(item, i) in list">索引:{{i}} --- 项:{{item}}</p>        <!-- 索引:0 --- 项:1             索引:1 --- 项:2             索引:2 --- 项:3             索引:3 --- 项:4             索引:4 --- 项:5             索引:5 --- 项:6 -->    </div>    <script>        var vm = new Vue({            el: '#app',            data: {                list: [1, 2, 3, 4, 5, 6]            },            methods: {}        });    </script></body>

8.2, V-for Loop Object array

<body>  <div id="app">    <p v-for="(user, i) in list">Id:{{ user.id }} --- 名字:{{ user.name }} --- 索引:{{i}}</p>  </div>  <script>    var vm = new Vue({      el: '#app',      data: {        list: [          { id: 1, name: 'zs1' },          { id: 2, name: 'zs2' },          { id: 3, name: 'zs3' },          { id: 4, name: 'zs4' }        ]      },      methods: {}    });  </script></body>

8.3. V-for Loop Object

<body>  <div id="app">    <!-- 注意:在遍历对象身上的键值对的时候, 除了 有  val  key  ,在第三个位置还有 一个 索引  -->    <p v-for="(val, key, i) in user">值是: {{ val }} --- 键是: {{key}} -- 索引: {{i}}</p>  </div>  <script>    var vm = new Vue({      el: '#app',      data: {        user: {          id: 1,          name: 'Tony Stark',          gender: '男'        }      },      methods: {}    });  </script></body>

8.4, V-for cycle number

<body>  <div id="app">    <!-- in 后面我们放过普通数组,对象数组,对象,还可以放数字 -->    <p v-for="count in 10">这是第 {{ count }} 次循环</p>  </div>  <script>    // 创建 Vue 实例,得到 ViewModel    var vm = new Vue({      el: '#app',      data: {},      methods: {}    });  </script></body>

Note: If you use the V-for iteration number, the preceding count value starts at 1.

8.5. V-for Loop Key Property

The key property allows each traversed item to be unique.

<body> <div id= "app" > <div> <label>id: <input type= "text" v-model= "id" >  </label> <label>name: <input type= "text" v-model= "Name" > </label> <input    Type= "button" value= "add" @click = "Add" > </div> <!--Note: When the v-for loop, the key property can only use number or string-- <!--Note: When key is in use, it must be in the form of the V-bind property binding, specifying the value of key--<!--in the component, using the V-for loop, or in some special cases, if v-for has a problem, you must use V-f Or, specify a unique string/number type: Key value--<p v-for= "Item in List": key= "Item.id" > <input type= "checkbox" >{ {Item.id}}---{{item.name}} </p> </div> <script>//Create Vue instance, get ViewModel var vm = new Vue ( {el: ' #app ', data: {ID: ', Name: ', list: [{id:1, Name: ' Reese '}, {        Id:2, Name: ' Win Politics '}, {id:3, name: ' Zhao Gao '}, {id:4, name: ' Han Fei '}, {id:5, Name: ' Xunzi '} ]}, methods: {Add () {///Add Method This.list.unshift ({id:this.id, name:this.name})}}); </script></body>

9, V-if/v-show

Both V-if and v-show can control the display or not of elements. But the implementation principle is different.

V-if: The element is re-deleted or created each time.

V-show: The DOM Delete and create operation is not re-performed each time, only the display:none style of the element is toggled.

Therefore, if the element involves frequent switching, it is best not to use v-if, but recommend the use of v-show;

It is recommended to use V-if if the element may never be displayed and is seen by the user.

Iv. Event Modifiers
    • .stop: Block bubbling

    • .prevent: Block default events (such as clicking on hyperlinks to prevent jumps to the default page)

    • .capture: Use event capture mode when adding event listeners (as opposed to bubbling mode)

    • .self: Triggers a callback when the event is triggered on the element itself (for example, not a child element)

    • .once: Event is triggered only once, then the behavior of the label itself is restored.

Example:

  <div id= "App" > <!--use. Stop to bubble-up <div class= "inner" @click = "Div1handler" > <input type= "button" value= "poke him" @click. stop= "Btnhandler" > </div> & lt;! --use. Prevent to block default behavior (jump to Baidu Home)--<a href= "http://www.baidu.com" @click. prevent= "LinkClick" > Have a problem, go to Baidu </first A> <!--use. Capture to implement a mechanism for capturing triggering events: In contrast to bubbling, from outside to the <div class= "inner" @click. capture= "Div1handler" &G            T <input type= "button" value= "poke him" @click = "Btnhandler" > </div> <!--use. Self to trigger an event only when the current element is clicked Processing functions--<div class= "inner" @click. self= "Div1handler" > <input type= "button" value= "poke him" @clic k= "Btnhandler" > </div> <!--use. Once triggers only one event handler (the following case only triggers one click event and then the behavior of the label itself)-<a href= "http://www.baidu.com" @click. prevent.once= "LinkClick" > Problems, first go to Baidu </a> </div>  

.stopand .self the difference:

        <!-- stop 会阻止冒泡行为 -->        <div class="outer" @click="div2Handler">            <div class="inner" @click="div1Handler">                <input type="button" value="戳他" @click.stop="btnHandler">            </div>        </div>        <!-- .self 只会阻止自己身上冒泡行为的触发,并不会真正阻止冒泡的行为 -->        <div class="outer" @click="div2Handler">            <div class="inner" @click.self="div1Handler">                <input type="button" value="戳他" @click="btnHandler">            </div>        </div>
V. Styles in Vue 1, class style
<!     DOCTYPE html>

Attention:

1. Class style requires the use of v-bind bindings.

2. Class style can be an array and a collection of objects.

2. Style styles

Can be an object, or an array of objects.

<body>    <div id="app">        <!-- 对象就是无序键值对的集合 -->        

Note: To bind to the style style.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.