vue VIII

Vuex

Vuex is a vue official state management tools, what is the state? We have in front-end development of a concept: data-driven, any display different pages, should have a data control, and this data is also called state, state.

In the vue. Inter-component data transfer, communication is very frequent, and communication functions and his son and his son assemblies and components are relatively non-perfect, but the only problem is that data sharing between multiple components to deal with this issue by the vuex

A global vue of state management tools provided by the major processing projects shared among multiple component status

Vuex use:
  1. Creating store:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


  1. Set state

state is a pure object, mounted on top of some state

import state from './state'
//可以设置store管理的state/getter,mutations,actions
const store = new Vuex.Store({
    state
})
  1. In instances where the root store configuration

In this way, we can pass this in any assembly. $ Store to store about the use of api

import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
  1. Used in the assembly state

Since the data may be used by the state management component in this.store.state

 data(){
    return {
        num:this.$store.state.num
    }
},

However, we found that this use of the words, when the state of the data changes, vue component and does not re-render

That is, if you want to type in the component response time of use, we need to calculate the property (computed) to use

computed:{
    num(){
        return this.$store.state.num
    }
}

Such wording is very boring, and if the state will have to use more redundancy feeling, so vuex provides mapState helper, help us obtain and use the store vuex stored in the component state

So we can write:

computed:mapState(['num']),

However, if the components have num this data, while the data in the name of state also called num will shine into conflict, this time when we can use components of the state, from the individual to the state name:

computed:mapState({
    // _num:'num',//键名为别名,值字符串代表的是真正的状态
    _num(state){//方法名为别名,函数体里还可以对真正的状态做出一些处理
        return state.num
    } //简写为  _num:state=>state.num
}),

However, sometimes we in the assembly also need to use their own business logic to calculate properties:

computed:{
    a(){
        return num+1
    },
    ...mapState({
        // _num:'num',//键名为别名,值字符串代表的是真正的状态
        _num(state){//方法名为别名,函数体里还可以对真正的状态做出一些处理
            return state.num
        }
    }),
},
  1. getters

Sometimes, we need to derive according to a state in a state of a new state, for example, our state has a num, in some components need to be used twice a num state, we can getters to create

const getters = {
    doubleNum(state){
        return state.num*2
    }
}

computed:{
    ...mapGetters(["doubleNum"])
}

Once you have created to get the data inside the component through this. $ Store.getters.doubleNum

Of course vuex also provides mapGetters helper to help us use getters in the state assembly, and, exactly the same methods used and mapState

  1. Use mutations change the state

We can not be changed directly in the assembly state:. This $ store.state.num = 2, but the need to change mutations, mutations are a pure object, which contains a lot of state change method, these methods shaped receiving state parameters , a function body changes, then, the component data is also used to change, responsive to achieve.

But we can not directly call mutations methods require the use of this. $ Store.commit invoked, the first argument for the method name to call, the second parameter to pass parameters ge

const mutations = {
    increment(state){
        state.num++
    }
}

vuex provides mapMutations ways to help the way we call mutations in the assembly, use and mapState, mapGetters as

  1. Use actions to handle asynchronous operation

Action similar mutation, except that:

Action is submitted mutation, rather than directly change state.
Action can contain any asynchronous operation.

That is, if there is such a demand: After an asynchronous process, change the status, we should call actions in the component to asynchronous operation, then called by the actions mutation to change data

const actions = {
    getNumFromBackEnd({commit}){
        setTimeout(() => {
            let num = Math.floor(Math.random()*10)
            //调用mutations的方法
            commit(CHANGE_NUM,num)
        }, 1000);
    }
}

Above, the method of operation Actions may be performed asynchronously, and participants received Store shaped, removed from the commit method for mutations of the method invocation

By this. Method $ store.dispatch method invocation actions in the component

Of course, you can also be used to aid in the use of mapMutations

Components use data and change data through a series of things asynchronous action:

1. Store generation, provided State
2. Store implantation in the root example
3. The components used state property, or by calculation mapState
A method to produce a user operation, the call actions, an asynchronous operation and then
after 5 asynchronous operation, the commit call methods mutations of
6.mutations method is called, change the state
after the data update 7.state in calculating property re-executed to change the page using state
8. component status change ... is to create a new virtual dom .. ....
template 9. after the update re-rendering components in the dom

vuex use:
There are two ways to use the situation on the market of vuex,

The first: the need to share the need to manage the state into the management vuex, that is used when necessary

The second: all data are handed over to vuex management to take on more responsibility vuex, become more lightweight components, lighter view layer


Custom command

In the implementation back to the top of the function, we wrote a backTop components, we need to control this component to display hidden events by listening window.scroll

Written a v-back-top command function is to make a return to the top of the directive, which requires the use of components or dom to return to the top, you can add this command to set different parameters to control in different situations under trigger

Vue component library

Component Library is a collection of common components

pc:element-ui iview

mobile: mint-ui

nextTick

When we use some plug-ins, it often needs to be carried out after dom update is complete the necessary operation, but provided vue in api only updated hook function, and in this function, the change of any data resulting dom update is complete triggers, it is likely to affect the unrelated data, and monitor the use of the words can only listen to the change data, dom has not been updated at this time, we can only use force to deal with setTimeout

Here we recommend the use nextTick global method:
execution delayed callback DOM after the end of the next update cycle. Using this method immediately after modifying the data, get the DOM updated.

eq:
getBillBoards(){
    axios.get(this.$root.config.host+'mz/v4/api/billboard/home',{
        params:{__t:Date.now()}
    }).then(res => {
        console.log(res.data.data.billboards)
        this.billboards = res.data.data.billboards

        //当数据更新,dom循环完成后,执行回调
        Vue.nextTick(function () {
            new Swiper('.app-home-banner',{
                loop:true
            }) 
        })
    })
}

Vue item analysis

  1. v-for traversing the display data can be achieved not only through the array, may traverse the object, the values ​​may be numerical values ​​from:

v-for = 'n in 10' n prints 1-10

  1. vue lifecycle hook:

通用:beforeCreate/created/beforeMount/mounted/beforeUpdate/updated/beforeDestroy/destroyed

Routing guard: beforeRouteEnter / beforeRouteUpdate (2.2 new) / beforeRouteLeave

  1. v-if v-show

v-if the condition is true rendering, it will ensure that the event listener within the conditional block in the handover, sub-assemblies will be destroyed and rebuilt appropriate

v-show will always render node in the dom, but based on css: display to show and hide control node

v-if there is a higher switching start, v-show has a higher initial cost of rendering

v-if inert, the initial condition is false, it will not render

  1. axios related

When the request does not bring axios Cookie, it does not affect the bandwidth, by withCredentials: set true

Axios request header to be set:

axios.defaults.headers = {'Content-Type':'...'}

vue2.0 not update and maintain vue-resource, the official recommended axios

  1. Scoped component instance is isolated, it means you can not (should not) reference data directly in the parent component sub-assembly template, make use subassemblies parent component data, the data needs to be passed to the child by the parent component of the props components, sub-assemblies can not and should modify the parent component of the incoming data, but to share data types of data can be passed by reference

6. In order for components may be combined, we need a way to mix the contents and sub-assemblies own template parent component. This process is referred to as content delivery (i.e. Angular user familiar "transclusion"). Vue.js implement a content distribution API, referring to the current Web Components draft specification, use the special <slot> element as the original content of the slot.

a-template:

<p>hello world</p>
<b>
    <h1>hello world</h1>
</b>

b-template:

<slot></slot>

  1. way to register:

Global: Vue.component (name, Vue.extend ({}))

局部:{ components:{name:Vue.extend({})} }

  1. Event Bus achieve non-parent-child communication components
//创建bus

let bus = new Vue()

//a

new Vue({
    template:'...',
    mounted(){
        bus.$on('emit-a',function(){
            alert(1)
        })
    }
})

//b

new Vue({
    template:'...',
    methods:{
        emitA(){
            bus.$emit('emit-a')
        }
    }
})
//当b组件的emitA方法被调用的时候,A组件就会执行alert(1)

  1. Difference calculation methods and properties

Suppose we have a data-num, but also want to have a data doublenum, and hope doublenum value of num is always twice

method:

* 因为是直接显示在模板中,也就是说,我们可以来一个doublenum的方法,这个方法返回num的二倍,将这个方法放到模板中的某个地方执行 {{doublenum()}}
  但是,当无关的例如一个str的数据更改的时候,组件会重新创建虚拟dom树,与上一次的虚拟dom树对比之后重新渲染,这个时候在重新渲染模板的时候doublenum函数会被再次的调用,造成不必要的性能浪费
  
* 创建一个doublenum数据,使其初始值为num的二倍,然后利用watch来监听这两个数据,在改变的时候更改对应的数据,但是需要初始的为doublenum赋值为num的二倍,如果num是动态获取到的,doublenun赋值会更繁琐

* computed计算数据,我们可以利用computed来创建一条新的doublenum数据。并且设置它的getter和setter,并与num建立关系,且computed会缓存,在重新渲染的时候,不会重新执行getter和setter
    computed:{
        doublenum:{
            get(){
                return this.num*2
            },
            set(val){
                this.num = val/2
            }
        }
    }
  1. Binding class object array syntax and grammar
<a :class="{a:true,b:false,c:1}"> => </a> => <a class='a c'></a>
    
data(){
    return {
        c:'c'
    }
}
<a :class = '["a","b",c]'></a> => </a> => <a class='a b c'></a>
  1. Unidirectional data flow

prop binding is unidirectional, parent component attribute change, is transmitted to the sub-assembly, however, subassembly data changes, the parent can not be directly transferred to the assembly, which is popular data flow is from the parent component sub-assembly, in order to prevent sub-assembly data modification parent component (rheological data will make the application more difficult to develop, update and maintain)

Vuex using tools when used during the data store in the component data flows are unidirectional, state-> vue component-> actions-> mutations-> state-> vue component

  1. this.$router.push/replace({name:'user',params:{userId:1})
    this.$router.push/replace({path:'/register',query:{plan:private})
key related

When the data changes, vue creates a new virtual dom dom to come and do the original virtual contrast, when creating a new virtual dom, it will have to look at the original virtual dom is not a part according to key, if the original there, this need will achieve reuse, and in doing diff contrast, if there is key will speed up the search speed contrast, improve performance

Do not try to time the cycle is set to be key index of the array, because when deleting a certain element of time, it will lead to key values ​​for all elements are deleted and the following location on a different virtual dom of key values, leading to reuse failure, this time we best use the unique key, such as key data such as id

If the variation value of data changes only and not change the number of positions and may be used as the key index

Vue.use()

Vue.use looks for plug-in object in the install method to execute and pass object to the install method in Vue

var a = {
    install(Vue){
        Vue.component("my-a",{...})
    }
}

Vue.use(a)
After entering the field displays different pages (PC / MOBILE) depending on the circumstances

In many cases, an application will have two versions of PC and mobile side, but the two versions because the difference is big, more content, but it can not be used alone to develop a responsive development, but only a domain name, the user directly back into the domain corresponding to device applications, there are two main approaches:

  1. Analyzing the front end and jump
    into the a blank page or an application, the device determines the type of user access through the navigator.userAgent, jump

  2. Analyzing the rear end of the corresponding application and in response
    returns a corresponding application after the user enters the domain of the address bar, the server can receive the head userAgent information request included, is determined

Guess you like

Origin blog.csdn.net/weixin_34033624/article/details/90779727