Vue personal project summary knowledge points (summary)

Article directory

Preface

This blog is a summary of the previous project related knowledge using Vue elementui webpack vuecli, i.e. personal project practical learning notes. After consulting relevant materials and self summarizing, this article is concluded. (if there are mistakes, please point out and study together)
Project source address: Click link

1. Vue life cycle

Image from: Vue.js lifecycle

Noun interpretation

Before create

Before data observation and initialization events start

created (after creation)

Complete data observation, property and method operations, initialize events, and the $el property has not been displayed

Before mount

Called before the mount starts, the related render function is called for the first time. The instance has completed the following configuration: compile the template and generate html from the data and template. Note that html has not been attached to the page at this time.

mounted (after loading)

After el is replaced by the newly created vm.$el, it is called after mounting to the instance. The instance has completed the following configuration: replace the DOM object pointed to by the El attribute with the html content compiled above. Complete the html rendering in the template to the html page. ajax interaction occurs during this process.

Before update

Before the data is updated, it occurs before virtual DOM is rendered and patched again. You can further change the state in this hook without triggering an additional re render pass.

updated (after update)

After the virtual DOM is rendered and patched due to data changes, it is called. When called, the component DOM has been updated, so you can perform DOM dependent operations. In most cases, however, you should avoid changing the state during this period, as this can cause an infinite loop of updates. The hook is not called during server-side rendering.

Before destroy

Before the instance is destroyed, it is called. The instance is still fully available.

destroyed (after destruction)

After the instance is destroyed, it is called. When called, all event listeners are removed and all child instances are destroyed. The hook is not called during server-side rendering.

Q & A

1. What is the vue life cycle?

A: the process from creation to destruction of Vue instances is the life cycle. A series of processes, such as creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, destroying, are called the life cycle of Vue.

2. What is the role of Vue life cycle?

A: it has multiple event hooks in its life cycle, which makes it easier for us to form good logic when controlling the process of the entire Vue instance.

3. How many stages are there in the Vue life cycle?

A: it can be divided into 8 stages: before / after creation, before / after loading, before / after updating, before / after destruction.

4. Which hooks will be triggered in the first page load?

A: the following before create, created, before mount, mounted will be triggered.

5. In which cycle has DOM rendering been completed?

A: DOM rendering is done in mounted.

2. Advantages of Vue

Low coupling

View can be changed and modified independently of Model. A ViewModel can be bound to different views. When the view changes, the Model can remain unchanged. When the Model changes, the view can also remain unchanged.

Reusability

You can put some view logic in a view model and make many views reuse this view logic.

Independent development

Developers can focus on business logic and data development (ViewModel), designers can focus on page design.

Testable

The interface is always more difficult to test, but now the test can be written for ViewModel.

3. Parameter transfer between Vue components

1. Value transfer between parent component and child component

The parent component is passed to the child component: the child component receives data through props method;
Child to parent: $emit method passes parameters

2. Data transfer between non parent and child components, and value transfer between brother components

eventBus is to create an event center, equivalent to a relay station, which can be used to pass and receive events. The project is relatively small, so it is suitable to use this one.

4. Jump between routes

Declarative (tag jump) programming (js jump)

5. How to customize a filter for Vue

html part code

<el-table-column label="Creation time" prop="add_time" width="140px">
       <template slot-scope="scope">
         {{scope.row.add_time | dateFormat}}
       </template>
</el-table-column>

In this project, the html page uses the element UI component and template to operate, and uses|to call the filter. Where add time is for background delivery.

data() {
   return {
     // Query parameter object
     queryInfo: {
       query: '',
       pagenum: 1,
       pagesize: 10
     },
     // Item list obtained from background
     goodslist: [],
     total: 0
   }
 }

Define filters globally

Vue.filter('dateFormat', function (originVal) {
 const dt = new Date(originVal)		//get data

 const y = dt.getFullYear()
 const m = (dt.getMonth() + 1 + '').padStart(2, '0')	//Fill 0 if less than two
 const d = (dt.getDate() + '').padStart(2, '0')

 const hh = (dt.getHours() + '').padStart(2, '0')
 const mm = (dt.getMinutes() + '').padStart(2, '0')
 const ss = (dt.getSeconds() + '').padStart(2, '0')

 return `${y}-${m}-${d} ${hh}:${mm}:${ss}`			//Return result
})

The filter takes the value of the expression (scope. Row. Add? Time) as the first parameter. The dateFormat filter will receive the value of msg as the first parameter.

6. The function of the key value of v-for in Vue

When Vue.js is updating the rendered list of elements with v-for, it defaults to the in place reuse policy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but simply reuse each element here and ensure that it displays each element that has been rendered under a specific index. key is mainly used to update virtual DOM efficiently.

7. What is Vue router used for

Vue router routing, generally speaking, is mainly to realize the page Jump, through setting different path s, sending different requests to the server, and obtaining different resources.
Main components: router view, router link

8. How to use custom components in vue.cli

9. How to write a Vue route from zero

In this project, the global definition is used.

1. Create a file in the components directory, as shown in the figure:

2. Define global routing information in router.js

Extract part (take the goods folder directory as an example)

1. Import vue and cue router first

import Vue from 'vue'
import VueRouter from 'vue-router'

2. Import in the required page

// import Cate from './components/goods/Cate.vue'
const Cate = () => import(/* webpackChunkName: "Cate_Params" */ './components/goods/Cate.vue')
// import Params from './components/goods/Params.vue'
const Params = () => import(/* webpackChunkName: "Cate_Params" */ './components/goods/Params.vue')

// import GoodsList from './components/goods/List.vue'
const GoodsList = () => import(/* webpackChunkName: "GoodsList_Add" */ './components/goods/List.vue')
// import Add from './components/goods/Add.vue'
const Add = () => import(/* webpackChunkName: "GoodsList_Add" */ './components/goods/Add.vue')

3. Register VueRouter

Vue.use(VueRouter)

4. Write routing information

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          component: Welcome
        },
        ......

5. Export module

export default router

10. Vue router hook function

The home page can control navigation jump, before each, after each, etc., which is generally used to modify the title of the page. Some need to log in to adjust page redirection.

beforeEach mainly has three parameters to, from, next:

To: the target routing object that route is about to enter,

from: route the route the current navigation is about to leave

Next: function must call the method resolve. The execution effect depends on the call parameters of the next method. You can control the jump of a web page.

Global: beforeEach, beforeResolve, afterEach
Routed: beforeEnter
Components: beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave

For example, the:

// Mount route navigation guard
router.beforeEach((to, from, next) => {
  // To the path to be accessed
  // From represents the path from which to jump
  // next is a function indicating release
  //     next() release next('/login') to force jump

  if (to.path === '/login' || to.path === '/') return next()
  // If the user accesses the non login path, judge whether there is a login certificate token
  const loginToken = sessionStorage.getItem('token')
  // No token, jump to login page directly
  if (!loginToken) return next('/login')
  // There's a token. Let's go
  next()
})

11. The principle of data bidirectional binding implemented by Vue: Object.defineProperty()

The implementation of data bidirectional binding in Vue is mainly as follows: in the way of data hijacking and publisher subscriber mode, the setter and getter of each property are hijacked through object. Defineproperty(). When the data changes, the message is published to the subscriber and the corresponding listening callback is triggered. When a normal Javascript object is passed to the Vue instance as its data option, Vue will traverse its properties and use Object.defineProperty to convert them to getter/setter. Users don't see getters / setters, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.

The data bidirectional binding of vue takes MVVM as the entry of data binding, integrates observer, Compile and watcher, monitors the data changes of its own model through observer, analyzes the compilation template instructions through Compile (vue is used to parse {}}), and finally uses watcher to build the communication bridge between observer and Compile to achieve data changes - > View update; view interaction change (input) - > data model change bidirectional binding effect.

js implements simple two-way binding

<body>
    <div id="app">
    <input type="text" id="txt">
    <p id="show"></p>
</div>
</body>
<script type="text/javascript">
    var obj = {}
    Object.defineProperty(obj, 'txt', {
        get: function () {
            return obj
        },
        set: function (newValue) {
            document.getElementById('txt').value = newValue
            document.getElementById('show').innerHTML = newValue
        }
    })
    document.addEventListener('keyup', function (e) {
        obj.txt = e.target.value
    })
</script>

12. How does the elementui do form validation

Examples in this project:

Validate user forms

html - demo:

 <!-- Add user -->
    <el-dialog title="Add user information" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- Content subject area -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="User name" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="Password" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="mailbox" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="Cell-phone number" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- Bottom area -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">Cancellation</el-button>
        <el-button type="primary" @click="addUser">Determine</el-button>
      </span>
    </el-dialog>

model binding form data

Get the data (editForm) by calling the background interface and database:

const { data: res } = await this.$http.get('users/' + id)
if (res.meta.status !== 200) {
     return this.$message.error('Failed to query user information!')
   }

   this.editForm = res.data		//get data

Get form value through prop

The following code:

<el-table-column label="Full name" prop="username"></el-table-column>
<el-table-column label="mailbox" prop="email"></el-table-column>
<el-table-column label="Telephone" prop="mobile"></el-table-column>
<el-table-column label="role" prop="role_name"></el-table-column>

Background API verification by writing ref

this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // Can initiate network requests to add users
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('Failed to add user information')
        } else {
          this.$message.success('Successfully added user information')
        }
        // Hide add user dialog
        this.addDialogVisible = false
        // Refresh user list
        this.getUserList()
      })
    }

Form content validation according to rules

The rules in the project are addFormRules, such as the following code (where checkMobile and checkEmail are verification methods written by themselves):

// Add form validation rule object
      addFormRules: {
        username: [
          { required: true, message: 'enter one user name', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: 'The length of the user name is 3~10 Between characters',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: 'Please input a password', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: 'The length of the user name is 6~15 Between characters',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: 'Please enter email', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: 'Please enter your mobile number', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }

13. How does Vue router redirect pages?

export default {
   path: '',
   name: '',
   meta: {  //Meta information (not required)
      icon: '',  //Routing Icon
      title: '',   //Routing name
      light: '',    //Highlight the route name
      show: true,   //Whether to display
   },
   redirect: {   
      name: '',    //Redirection, name of which route to point to
   },
   component: '',    //Components to display on current route
   children: [],    //Nested sub route
}

Practical application in the project:

14. Differences among Ajax, fetch and axios

ajax is the first technology to send back-end requests, which belongs to the category of native js. The core is to use XMLHttpRequest object. If it is used more and in order, it is easy to generate a callback to hell.

fetch is designed based on Promise object in ES6. Its parameters are similar to ajax in jQuery. It is not a further encapsulation of ajax. It belongs to the category of native js. XMLHttpRequest object is not used.

axios is not a native js. It needs to be installed when it is used. It can be used by both the client and the server. It can be intercepted in the request and corresponding stages, based on Promise object.

15. How to make css work only in the current component

Write scoped in the style tab, for example:

<style lang="less" scoped></style>

Reference material

In the interview of Vue, the interview questions / knowledge points of Vue that are often asked are sorted out (source: Jianshu)
vue 248 knowledge points (interview questions) to escort you (source: Nuggets)

164 original articles published, 55 praised, 30000 visitors+
Private letter follow

Tags: Vue Mobile axios less

Posted on Mon, 09 Mar 2020 04:06:42 -0400 by tromton