“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

Using the vue for over a year, this is for a checking before, detailed content there is no official document, for the vue probably just stay in the use of stage, also does not have too much attention, the source code (this is also need to increase), the content of this article may exist a lot of shortcomings, hope leaders can help to correct me, let I think I can improve it. It’s really easier to write than to write, and the replay feels not so clear, but it’s also a summary

The data processing

Recommended several library time handling recommended day.js data handling lodash

instruction

What kinds of instructions are available in VUE?
v-html v-text v-if v-else v-else-if v-show v-for v-on v-bind v-model v-slot v-pre v-cloak v-once
Copy the code
V – – HTML text and v

Similarities Both can render data, but V-HTML can parse tags

<span v-text=" MSG "></span> <span v-html="htmlMsg"></span> data(){return{MSG :' I am a span tag ' HtmlMsg :'<strong> I am a span tag </strong>'}}Copy the code
V-if and V-for are not recommended for the same element

When they are on the same node, V-for takes precedence over V-IF, which means that V-IF will run separately in each V-for loop.

v-if vs v-show

V-show controls the display or hiding of DOM nodes through CSS display, and V-if controls the existence of DOM nodes. V-show is used frequently, or V-if is used otherwise

V – for the key

Adding unique identifiers to DOM nodes can effectively update the virtual DOM

v-model

Essentially syntactic sugar that generates different events and attributes depending on the tag

<input V-model ="currentValue"> = <input V-bind :value="currentValue" V-ON :input="currentValue = $event.target.value">Copy the code
v-cloak

Prevents variable names from flashing first when the page loads

The life cycle

An overview of the
What are the life cycles in VUE?
Created completes the initialization of data after the beforeCreate instance is initialized. BeforeMount The related render function is called when the HTML is not mounted on the page. BeforeUpdate before data is updated Updated after data update. beforeDestroy Called before instance destruction, reset operation, clear timer and listener operation destroyed after destructionCopy the code
Listen for the internal lifecycle outside the component

Previously, we wanted to listen for the internal lifecycle of the component. We might have chosen to emit in the corresponding lifecycle hook and then listen externally. In fact, we can directly listen for the corresponding lifecycle through hook events

<base-button @hook:created="createBtn" label=" main button "></base-button>Copy the code
Mounted and created which are better suited for Ajax requests

I have never cared about this before, until I once saw a question about this, I suggested to use it in Mounted, do I feel that I have put it in the wrong place? According to some data, there is not much difference. In order to avoid flash screen and CREATED consistency (SSR), you need to operate DOM in Mounted.

Created manipulates the DOM

You can use $nextTick to defer the callback until after the next DOM update cycle

this.$nextTick(()=>{... })Copy the code
nextTick

Promise.then, MutationObserver, and setImmediate do not support setTimeout. The first two are microtasks and the second two are macro tasks

Style binding

We can display the corresponding styles in the form of objects, in the form of arrays, in terms of conditions

<div class="base-button-container" :class="[{'disabled':disabled}]" :style="{'margin':margin}"> data(){return{ margin:'15px', <div class="base-button-container" :class="[disabled]" :style="[baseStyle]"> data(){return{ baseStyle:{ color:'red' }, <div class="base-button-container" :style="{'margin':isBorder? '0':'15px'}"> data(){return{ isBorder:false }}Copy the code

vue-router

beforeEach

Processing authentication (to see if tokens exist) filters the routing table based on the user’s permissions

From vue-element-admin router. BeforeEach (async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history recordnext({ ... to,replace: true})}catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login? redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if(whiteList.indexOf(to.path) ! = = -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login? redirect=${to.path}`)
      NProgress.done()
    }
  }
})

Copy the code
The difference between hash and History modes

The most obvious difference is that in hash mode, the URL contains a ‘#’. In history mode, the front-end URL must be the same as the back-end URL for initiating requests. The default is hash mode

Routing by value

Scenario: Route redirection displays product details

Data is not lost when the page is refreshed. $router.push({query$route.query.X: $route.push ({}})params:{}}) The data carried by the refreshed page will be lostCopy the code

vueX

Vuex is a state management pattern usage scenario developed specifically for vue.js applications: multiple views depend on the same state. Actions from different views need to change the same state.

Five core attributes?
State, getters, mutations, Actions, modules.Copy the code

Vuex initializes and resets data during UI refresh. In this case, you need to store data in localStorage or sessionStorage

SessionStorage data is preferred during initializationconst state = {
  state1: JSON.parse(sessionStorage.getItem('state1')) || null} mutations to update the data in sessionStorageSET_STATE1: (state, keyData) = > {
    sessionStorage.setItem('state1'.JSON.stringify(keyData))
    state.state1 = keyData
  },
Copy the code
In-component use
this.$store.state.xx
this.$store.getters.xx // Similar to calculating attributes
Copy the code
Modify the

Display the COMMIT mutation or Dispatch action to modify the data in state

this.$store.commit('SET_STATE1', keyData) SET_STATE1 is defined for mutations
this.$store.dispatch('SET_STATE1'.null) SET_STATE1 is defined for actions
Copy the code

axios

Params mass participation

When you pass an array, you need a=1&a=2&a=3

Qs.stringify serializes the object into the form of a URL qs.stringify({a: ['1'.'2'.'3'] {},indices: false });
Copy the code
encapsulation
  return request({
    url: ' '.method: 'get'Request.js creates an AXIos request and adds a token to the request. Reponse handles the content returned by the request. The following content comes from vue-element-admin and is readily available with thisconst service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
Copy the code

componentization

How many ways does a component pass value?
Cross component Event Bus VUex state management implements communication between props and EMIT instances $parent,$childrenCopy the code
Attrs and listeners

Element components need to be encapsulated twice. If all properties need to be passed to the internal Element component via props, the process can be very complex. Attrs and attrs and listeners can be transmitted across layers

    <div class="base-table-container">
        <el-table :data="list" v-on="$listeners" v-bind="$attrs" >
            <slot></slot>
        </el-table>
    </div>
Copy the code

conclusion

Again, I recommend reading the document. I will have a clearer understanding of the concept and some details. I seem to have left a lot of things behind in this rewritten article, so I will try to improve it later.