vue basis -2

Computed Property

(1) Examples of base

Sometimes we need to use a data template, this time you need to use the expression, but in some places we need a few simple data processing before use, then we will write some js in expression logic operation

<div id="example">
 {{ message.split('').reverse().join('') }}
</div>

So our maintenance will be very difficult, not easy to read

(2) calculation register vs methods

We can set up a method in the methods, the use of this method in an expression template

// 在组件中
methods: {
    reversedMessage: function () {
        return this.message.split('').reverse().join('')
    }
}

But this time, as long as the data changes vm, this data may change and data unrelated to our attention, but will re-render vm template, this time method expression will be re-run, greatly affect performance

(3) data vs computed vs watch

In fact, we can use this time in the listener complete:

Vm watch the setting property instance, in which to set some monitoring through key-value pairs, called the data key name, value may be a function that will be performed after the data is changed, two parameters are the value before the change and the changed value

 watch:{
        a: function (val, oldVal) {
            console.log('new: %s, old: %s', val, oldVal)
        }
    }

Value can also be a method name, when the data changes this method will be executed

When the data object is a time, the key changes to the object is not monitored (push array method and the like may be), this time need to set the depth monitoring:

c: {
        deep:true,
        handler:function (val, oldVal) {
            console.log('new: %s, old: %s', val, oldVal)
        }
    },

Listening in front of the handler function of these types are written will be performed when the data changes, the initialization time will not be executed, but if you set it to true immediate

watch:{
        num(newValue,oldValue){ //这样去写的话不会主动执行一次,需要更改依赖项的时候,才会执行!
        },
        num:{
            immediate:true, //初始化的时候主动执行一次handler
            handler:function(newValue,oldValue){
                this.nums = newValue*2
            }
        }
    }

We return to the above problems, coupled with the immediate property listener can do this effect, but we can see is a little bit complicated logic

We usually use a thing called computed attribute to solve:

Is provided to calculate the property instance of the configuration item vm computed by a new data, the new data and this will have a dependency (data of one already exists), when dependent changes, new data will change

Compared with the method, the higher its performance is calculated based on their properties are dependent caching. Calculation of property will only be re-evaluated when it changed its dependencies. In contrast, whenever the trigger re-rendering, calling the method will always execute the function once again.

Compared with the watch, to write simple, logical and clearer, watch generally used, and perform some action based on the data changes, and whether these actions are doing really does not matter, calculated attribute more targeted, according to data changes and another change data

Calculate property also has a getter and setter, the default is to write getter, setter can set the property when the data changes this calculation to do some other things, this calculation is equivalent to watch property

 xm:{
        get:function(){//getter 当依赖改变后设置值的时候
            return this.xing+'丶'+this.ming
        },
        set:function(val){//setter 当自身改变后执行
            this.xing = val.split('丶')[0]
            this.ming = val.split('丶')[1]
        }
    }

Mixins

Mixed (as mixins) is a very flexible assembly Vue manner distributed multiplexing functions.

Mixed objects can contain any component options.

When a component uses mixed object, all objects will be mixed with the options of the option component itself is mixed.

	<div id="app">
    	<button @click="a">a</button>
    	<p>{{b}}</p>
    </div>
  
    <script src="./base/vue.js"></script>
    <script>

      //在Vue里可以使用mixins来做代码的抽离复用,便于维护
      //一个mixin其实就是一个纯粹的对象,上面挂载着抽离出来的配置,
      //在某一个实例中,通过mixins选项导入后,此实例就拥有导入的mixin的配置
      //并且不会与原配置相互覆盖,而是合并到一起

      let common = {
        methods:{
          a(){
            console.log("a执行了")
          }
        },
        computed:{
          b(){
            return "b"
          }
        }
      }


      new Vue({
        el:"#app",
        mixins:[common]
      })
      
    </script>

Data Request

(1) vue-resource request

Starting from 2.0 vue, the authors say: vue-resource no longer maintained

(2) fetch request (specification)

why: XMLHttpRequest is a rough design of API, configuration and invocation very confusing, but also to write event-based asynchronous model unfriendly.

Check Compatibility: https://caniuse.com/#search=fetch

Compatibility is not good polyfill: https://github.com/camsong/fetch-ie8

1 //get
2 fetch("**").then(res=>res.json()).then(res=>{console.log(res)})
3 fetch("**").then(res=>res.text()).then(res=>{console.log(res)})


4 //post
5 fetch("**",{
6 method:'post',
7 	headers: {
8 		"Content‐Type": "application/x‐www‐form‐urlencoded"
9 	},
10 	body: "name=zhangsan&age=100"
11 	}).then(res=>res.json()).then(res=>{console.log(res)});


12 fetch("/users",{
13 	method:'post',
14 	// credentials: 'include',
15 	headers: {
16 	"Content‐Type": "application/json"
17 },
18 	body: JSON.stringify({
19 		name:"zhangsan",
20 		age:100
21 	})
22 }).then(res=>res.json()).then(res=>{console.log(res)});

** Fetch request the default is not with the cookie, to set fetch (url, {credentials: 'include'}) *

(3) axios request

// get
axios.get("json/test.json?name=zhangsan&age=10").then(res=>{
    // res.data 才是真正的后端数据
    console.log(res.data.data.films)
    this.datalist = res.data.data.films
})


//post -1- x-www-form-urlencode
axios.post("json/test.json","name=zhangsan&age=10").then(res=>{
	console.log(res.data)
})

//post -2- application/json
axios.post("json/test.json",{
    name:"zhangsan",
    age:100
}).then(res=>{
    console.log(res.data)
})

COMPONENTS

(1) Components of

Modular system functionality is separated into individual functional parts of the process, generally it refers to a single one thing, e.g. js, css

For the assembly of the entire page is fully functional module division, is a component html, css, js, image endures chain resources, a part of these polymeric

Advantages: code reuse, easy to maintain

The principle of division of components: reuse high, strong independence

Components should have features: can be combined, reusable, testable, maintainable

(2) Component

In vue, we are through to create a subclass of the Vue Vue.extend , this thing is actually a component

That instance Vue instances and components of a difference but not very different, because after all, is a parent class is a subclass

General application, will have a root instance, it is an example of the inside of a root component

Because the components are to be embedded in the examples, or the parent component, i.e., the component can be nested with each other, and all components must have a root outermost example, they are divided into components: local and global components assembly

Global components can be used in any instance, the parent component, sub-assembly can only create their own parent or components used in the examples

Creating components:

Vue.extend(options)

Global registration:

var App = Vue.extend({
	template:"<h1>hello world</h1>"
})
Vue.component('my-app',App)

Simple wording:

// 创建组件构造器和注册组件合并一起  
Vue.component('hello',{//Vue会自动的将此对象给Vue.extend
	template:"<h1>hello</h1>"
})

Components to determine their own templates by template, template in the template must have a root node, the label must be closed

Properties of a component mounted by: a method to return data as an attribute of an object component, the aim is to have each separate component instance attribute data

Local registration:

new Vue({
    el:"#app",
    components:{
    	'my-app':App
    }
})

Simple wording:

 data:{},
    components:{
        'hello':{
            template:"<h1>asdasdasdasdasdas</h1>"
        }
    }

Registered in another component or component instance, this time, only the component is registered in the registered template instance or its components is used, a component or components may be registered multiple instances

Note Browser rule

Since vue template parsing time will be according to the rules of some html, for example, in the table can only be put in tr, td, th ..., if not resolved into components at this time we can put to use is tr way to identify this tr actually components

<table id="app">
    <tr is="hello"></tr>
</table>

template

<template id="my-hello">
    <div>
        <h1>hello world</h1>
        <p>hahahah</p>
    </div>
</template>
//组件中
template:"#my-hello"

is switched

On the template instance, one of the components of the label, may be specified by the component attribute is another goal, this time we will generally use the component tag placeholder, set the attribute to specify the target component is

<component :is="type"></component>

//组件中
data:{
    type:'aaa'
},
components:{
    'aaa':{template:"<h1>AAAAAAAAAAAAA</h1>"},
    'bbb':{template:"<h1>BBBBBBBBBBBBB</h1>"}
}

Nested Components

Divided in many application components may, in order to better achieve code reuse, so there is bound to components nesting relationship

The most common is the relationship between father and son form a component assembly is designed to be used in conjunction with: A component used in the assembly of its template B.

(3) Filter

may be provided vue filter (filter) to implement the data format, bis braces and v-bind interpolation used in the expression

vue1.0 have default filter, when all but 2.0 to remove the

So vue If you want to use the filter you need to customize

Custom method of two types: global and local definitions defined,
globally defined filters can be used in any example, components,
locally defined is defined in the example, the assembly, only in this instance or component

  1. Global definition

    Vue.filter (name, handler)

    name is the name of the filter, handler processing data formatting function, the first parameter data to be processed is received, returns any data, formatted result is what

    Used to transfer (pipe symbol), added after the name of the filter () parameter, the second parameter and subsequent to receiving the parameter handler function | template by

 <p>{{msg | firstUpper(3,2)}}</p>

Vue.filter('firstUpper',function (value,num=1,num2) {
	console.log(num2)
	return value.substr(0,num).toUpperCase()+value.substr(num).toLowerCase()
})
  1. Local definition

    Filters disposed in the configuration item instances, assembly, key named filter name, value handler

    filters:{
        firstUpper:function (value,num=1,num2) {
        console.log(num2)
        return value.substr(0,num).toUpperCase()+value.substr(num).toLowerCase()
        }
    }

(4) Virtual dom

Dom frequent and complex operating normally produced front-end performance bottleneck point, Vue provides a solution to the virtual dom

Virtual DOM core idea is: complex document DOM structure that provides a convenient tool, minimizing the DOM manipulation. This sentence, perhaps too abstract, but a basic overview of virtual DOM design ideas

(1) provide a convenient tool so that the development efficiency can be guaranteed
(2) to ensure the operation of minimizing DOM, so efficiency is assured

In other words, the virtual dom frameworks / tools are doing:

  1. According to the first rendered as a virtual tree dom dom real
  2. When the data changes, or a need to re-render the page when will regenerate a new complete virtual dom
  3. Take a new virtual dom dom to do the old virtual and contrast (using diff algorithm). After getting the place needs to be updated, updates

In this case, it can significantly reduce operating real dom improve performance

What is a virtual dom? Relationships with key value?
Virual DOM is a copy of a record dom node with JS objects, when dom changes, first
performed diff virtual dom, calculate the minimum difference, and then modify the real dom.

当用传统的方式操作DOM的时候,浏览器会从构建DOM树开始从头到尾执行一遍流程,效率很低。而虚拟DOM是用javascript对象表示的,而操作javascript是很简便高效的。虚拟DOM和真正的DOM有一层映射关系,很多需要操作DOM的地方都会去操作虚拟DOM,最后统一一次更新DOM。因而可以提高性能

Virtual dom summarized understand

Relations with the key of the virtual dom

Published 21 original articles · won praise 0 · Views 292

Guess you like

Origin blog.csdn.net/weixin_43861707/article/details/104998934