Front-end vue tutorial (detailed version)

Vue

1. What is Vue

Vue is a progressive JavaScript framework

  • Vue is a progressive JavaScript framework that can be used to build user interfaces.
  • Vue is easy to learn, lightweight, efficient, and flexible.
  • Vue adopts the MVVM model and realizes component development through data-driven views.
  • Vue has a rich ecosystem, such as Vue Router, Vuex, Vue CLI, etc.
  • Vue supports server-side rendering, TypeScript and other features to meet different development needs.

Vue can be used to build user interfaces

  • Vue is a progressive framework for building user interfaces. It adopts the MVVM pattern, drives views through data, and provides responsive and componentized ideas, making it easier for developers to build interactive applications.

  • Vue can be used to build user interfaces. It provides a series of instructions and components, including v-bind, v-model, v-if, v-for, etc., and also supports custom instructions and components. Through these instructions and components, developers can quickly build various types of user interfaces, such as forms, lists, navigation, and so on.

Vue's core library focuses only on the view layer - Vue's core library focuses only on the view layer, so it's easy to learn and integrate into other projects.

  • Vue uses virtual DOM to optimize performance and provides responsive and componentized development.
  • Vue supports template syntax and JSX syntax, and can be seamlessly integrated with other libraries and frameworks.

2. Features of Vue

  1. progressive framework
  2. Data Driven View
  3. Component development
  4. lightweight
  5. easy to use

3. The basic grammar of Vue

template syntax

  • Interpolation expression: { { }}
    <div>{
          
          {
          
           message }}</div>
    
  • v-bind directive: bind data to attributes of HTML elements
    <img v-bind:src="imageSrc">
    
  • v-if directive: Conditionally render elements based on the true or false value of an expression
    <div v-if="isShow">显示的内容</div>
    
  • v-for directive: render list
    <ul>
    <li v-for="item in items">{
          
          {
          
           item }}</li>
    </ul>
    
  • v-on directive: bind event
    <button v-on:click="handleClick">点击</button>
    
  • Computed property: computed
    <div>{
          
          {
          
           reversedMessage }}</div>
    ...
    computed: {
          
          
      reversedMessage: function () {
          
          
        return this.message.split('').reverse().join('')
      }
    }
    
  • Listening attribute: watch
    watch: {
          
          
     message: function (newVal, oldVal) {
          
          
       console.log('message changed from', oldVal, 'to', newVal)
     }
    }
    
  • Life cycle: created, mounted, updated, destroyed
    created: function () {
          
          
    console.log('组件实例创建完成')
    },
    mounted: function () {
          
          
    console.log('组件挂载到DOM上')
    },
    updated: function () {
          
          
    console.log('组件更新')
    },
    destroyed: function () {
          
          
    console.log('组件销毁')
    }
    

instruction

  • v-bind directive: used to bind attribute values, such as binding src, href, etc.
  • v-model directive: used to implement two-way binding of form data
  • v-if instruction: used to judge whether to render elements according to conditions
  • v-for directive: used to loop rendering elements
  • v-on directive: used to bind event listeners, such as @click, @keyup, etc.
  • v-show command: used to determine whether to display elements according to conditions
  • v-text directive: used to set the text content of an element to a specified value
  • v-html directive: used to set the HTML content of the element to the specified value
  • v-pre instruction: used to skip the compilation process of the specified element and its sub-elements, which can be used to optimize performance
  • v-cloak instruction: used to prevent page flashing, can be used in conjunction with CSS
  • v-once instruction: used to render elements only once, without re-rendering as the data changes

Form syntax:

command name describe
v-bind for binding property values
v-model Two-way binding for form data
v-if Used to determine whether to render elements based on conditions
v-for Used to loop through elements
v-on Used to bind event listeners
v-show Used to determine whether to display elements based on conditions
v-text Used to set the text content of an element to a specified value
v-html Used to set the HTML content of an element to a specified value
in-for Used to skip the compilation process of the specified element and its children
v-cloak Used to prevent page flickering
v-once Used to render the element only once

components

  • components

    • Example 1:

      <template>
      <div>
        <h1>{
              
              {
              
              title}}</h1>
        <p>{
              
              {
              
              content}}</p>
      </div>
      </template>
      
      <script>
      export default {
              
              
      data() {
              
              
        return {
              
              
          title: '这是标题',
          content: '这是内容'
        }
      }
      }
      </script>
      
    • Example 2:

      <template>
       <div>
         <input v-model="message">
         <p>{
              
              {
              
              message}}</p>
       </div>
      </template>
      
      <script>
      export default {
              
              
       data() {
              
              
         return {
              
              
           message: ''
         }
       }
      }
      </script>
      

life cycle

  • life cycle

    A Vue instance has a complete life cycle, that is, a series of processes from the beginning of creation, initialization of data, compilation of templates, mounting of Dom, rendering, update, uninstallation, etc. We call this the life cycle of Vue. Commonly used life cycles are as follows:

    1. beforeCreate: After instance initialization, before data observer and event/watcher event configuration is called.

    2. created: Called after the instance has been created. In this step, the instance has completed the following configurations: data observer, operation of attributes and methods, watch/event event callback. However, the mount phase has not yet started, and the $el property is not currently visible.

    3. beforeMount: Called before the mount starts: the relevant render function is called for the first time.

    4. mounted: el is replaced by the newly created vm.$el, and this hook is called after it is mounted on the instance.

    5. beforeUpdate: Called when the data is updated, before the virtual DOM is re-rendered and patched. Further state changes can be made within this hook without triggering additional re-rendering passes.

    6. updated: This hook will be called after the virtual DOM is re-rendered and patched due to data changes.

    7. beforeDestroy: Called before the instance is destroyed. At this step, the instance is still fully available.

    8. destroyed: Called after the instance is destroyed. At this point, all commands have been unbound, all event listeners have been removed, and all child instances have been destroyed.

computed property

  • computed property

    <template>
      <div>
        <p>{
          
          {
          
           message }}</p>
        <p>{
          
          {
          
           reversedMessage }}</p>
      </div>
    </template>
    
    <script>
    export default {
          
          
      data() {
          
          
        return {
          
          
          message: 'Hello World'
        }
      },
      computed: {
          
          
        reversedMessage() {
          
          
          return this.message.split('').reverse().join('')
        }
      }
    }
    </script>
    

    Here we define a computed property reversedMessage that returns the reversed string of the message. In the template, we can use reversedMessage directly without writing logic code in the template to realize the function of reversing the string. The value of a computed property is cached and re-evaluated only when the associated dependency changes.

Listener - Basic usage of Listener:
var vm = new Vue({
    
    
  data: {
    
    
    message: 'Hello'
  },
  watch: {
    
    
    message: function (newVal, oldVal) {
    
    
      console.log('newVal: ', newVal, ' oldVal: ', oldVal)
    }
  }
})
  • Deep monitoring:

    var vm = new Vue({
          
          
      data: {
          
          
        obj: {
          
          
          a: 1
        }
      },
      watch: {
          
          
        'obj.a': function (newVal, oldVal) {
          
          
          console.log('newVal: ', newVal, ' oldVal: ', oldVal)
        }
      }
    })
    
  • Execute the listener immediately:
    var vm = new Vue({
          
          
      data: {
          
          
        message: 'Hello'
      },
      watch: {
          
          
        message: {
          
          
          handler: function (newVal, oldVal) {
          
          
            console.log('newVal: ', newVal, ' oldVal: ', oldVal)
          },
          immediate: true
        }
      }
    })
    

4. Advanced usage of Vue

custom directive

  • custom directive

    // 注册一个全局自定义指令 `v-focus`
    Vue.directive('focus', {
          
          
    // 当绑定元素插入到 DOM 中。
    inserted: function (el) {
          
          
      // 聚焦元素
      el.focus()
    }
    })
    
    // 局部注册一个自定义指令
    directives: {
          
          
    focus: {
          
          
      // 指令的定义
      inserted: function (el) {
          
          
        el.focus()
      }
    }
    }
    

plug-in

  • Plugins:
    • Vue Router: The official routing manager of Vue.js for building single-page applications.
    • Vuex: The official state management library of Vue.js, which is used to centrally manage the state of all components of the application.
    • Vue CLI: The official scaffolding tool provided by Vue.js for quickly building Vue.js applications.
    • Vue Test Utils: Vue.js official testing tool library for writing unit tests and integration tests.
    • Element UI: A set of Vue.js-based component libraries that provide rich UI components and interactive effects.
    • Vue-i18n: The official internationalization plug-in provided by Vue.js, which is used to realize the multi-language support of the application.
    • Vue-meta: A plug-in officially provided by Vue.js for managing page meta information, which can easily set page title, keywords, description and other information.
    • Vue-lazyload: A plugin for lazy loading of images, which can improve page loading speed and user experience.
    • Vue-axios: A plugin officially recommended by Vue.js for initiating HTTP requests, which can easily interact with the backend API.
    • Vue-socket.io: A plug-in for WebSocket communication, which can realize real-time communication and data interaction.

mixin

  • mixin

    Mixins are a way of reusable functionality provided by Vue, which allow us to combine a set of component options into a single object, which can then be used as options in multiple components. This allows us to share the same options across multiple components, avoiding duplication of code.

    // 定义一个mixin对象
    const myMixin = {
          
          
      created() {
          
          
        console.log('mixin created')
      },
      methods: {
          
          
        foo() {
          
          
          console.log('mixin foo')
        }
      }
    }
    
    // 在组件中使用mixin
    export default {
          
          
      mixins: [myMixin],
      created() {
          
          
        console.log('component created')
      },
      methods: {
          
          
        bar() {
          
          
          console.log('component bar')
        }
      }
    }
    

    In the above example, we defined a mixin object named myMixin, which contains a created hook function and a method named foo. Then, we use the mixins option in the component to mix myMixin into the component. Finally, the component contains the options defined in myMixin, while also retaining the component's own options.

    When the component and mixin contain the same options, the component's options will override the options in the mixin. If we want to call the method in the mixin in the component, we can use $emit to trigger the method in the mixin.

    export default {
          
          
      mixins: [myMixin],
      created() {
          
          
        this.$emit('foo')
      }
    }
    

Transitions and Animations

  • Basic usage of Vue transition
    <transition>
    <p v-if="show">hello</p>
    </transition>
    
  • CSS class names for Vue transitions
    <transition name="fade">
     <p v-if="show">hello</p>
    </transition>
    
  • JS hook function for Vue transition
    <transition
      v-on:before-enter="beforeEnter"
      v-on:enter="enter"
      v-on:after-enter="afterEnter"
      v-on:enter-cancelled="enterCancelled"
    >
      <p v-if="show">hello</p>
    </transition>
    
  • Basic usage of Vue animation
    <transition name="fade" mode="out-in">
     <p :key="message">{
          
          {
          
           message }}</p>
    </transition>
    
  • JS hook function for Vue animation
    <transition
     v-on:before-enter="beforeEnter"
     v-on:enter="enter"
     v-on:after-enter="afterEnter"
     v-on:enter-cancelled="enterCancelled"
    >
     <p :key="message">{
          
          {
          
           message }}</p>
    </transition>
    
  • Multiple element animation for Vue animation
    <transition-group name="list" tag="ul">
    <li v-for="item in items" :key="item">{
          
          {
          
           item }}</li>
    </transition-group>
    
  • Custom CSS class names for Vue animations
    <transition
     name="fade"
     enter-active-class="animated fadeIn"
     leave-active-class="animated fadeOut"
    >
     <p v-if="show">hello</p>
    </transition>
    
  • Custom JS hook function for Vue animation
    <transition
      v-on:before-enter="beforeEnter"
      v-on:enter="enter"
      v-on:after-enter="afterEnter"
      v-on:enter-cancelled="enterCancelled"
      v-on:before-leave="beforeLeave"
      v-on:leave="leave"
      v-on:after-leave="afterLeave"
      v-on:leave-cancelled="leaveCancelled"
    >
      <p v-if="show">hello</p>
    </transition>
    

routing

  • Routing basic usage example:
// 安装路由
npm install vue-router --save

// 引入路由
import VueRouter from 'vue-router'

// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/',
      component: Home
    },
    {
    
    
      path: '/about',
      component: About
    }
  ]
})

// 注册路由
new Vue({
    
    
  router,
  render: h => h(App)
}).$mount('#app')
  • Example of route nesting usage:
// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/',
      component: Home,
      children: [
        {
    
    
          path: 'child',
          component: Child
        }
      ]
    }
  ]
})
  • Example of dynamic routing usage:
// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/user/:id',
      component: User
    }
  ]
})

// 跳转路由
this.$router.push('/user/123')
  • Example of named route usage:
// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/',
      component: Home,
      name: 'home'
    }
  ]
})

// 跳转路由
this.$router.push({
    
     name: 'home' })
  • Example of using route parameters:
// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/user/:id',
      component: User
    }
  ]
})

// 跳转路由
this.$router.push({
    
     path: '/user/123', query: {
    
     name: '张三' } })

// 接收参数
this.$route.params.id // 123
this.$route.query.name // 张三
  • Example of lazy loading of routes:
// 配置路由
const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/user',
      component: () => import('./User.vue')
    }
  ]
})
  • Example of route guard usage:
// 全局前置守卫
router.beforeEach((to, from, next) => {
    
    
  // 判断是否登录
  if (to.path !== '/login' && !isLogin) {
    
    
    next('/login')
  } else {
    
    
    next()
  }
})

// 全局后置守卫
router.afterEach((to, from) => {
    
    
  // 统计PV
  pv++
})

Vuex state management - Vuex state management

Vuex is Vue's official state management library for managing the state of all components of the application. It centralizes the application's state in a single place, making state changes easier to track and debug. Here is an example of simple Vuex state management:

// 定义一个Vuex store
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment(state) {
    
    
      state.count++
    }
  },
  actions: {
    
    
    incrementAsync({
     
      commit }) {
    
    
      setTimeout(() => {
    
    
        commit('increment')
      }, 1000)
    }
  },
  getters: {
    
    
    doubleCount(state) {
    
    
      return state.count * 2
    }
  }
})

// 在Vue组件中使用Vuex
<template>
  <div>
    <p>Count: {
    
    {
    
     count }}</p>
    <p>Double count: {
    
    {
    
     doubleCount }}</p>
    <button @click="incrementCount">Increment count</button>
  </div>
</template>

<script>
export default {
    
    
  computed: {
    
    
    count() {
    
    
      return this.$store.state.count
    },
    doubleCount() {
    
    
      return this.$store.getters.doubleCount
    }
  },
  methods: {
    
    
    incrementCount() {
    
    
      this.$store.commit('increment')
    }
  }
}
</script>

In the example above, we defined a simple Vuex store with a state countand a incrementmutation to increment countthe value. We also define an incrementAsyncaction for asynchronously incrementing countthe value. Finally, we define a doubleCountgetter for computing countthe double. In Vue components, we use computedproperties to get the value of state and getters, and use methodsproperties to trigger mutations.

5. Vue's Ecosystem

View CLI

  • Vue CLI is an official command-line based tool for quickly building Vue.js projects.
  • It can help us generate the infrastructure of the Vue project, including webpack configuration, routing, state management, etc.
  • Vue CLI also provides a wealth of plug-ins and preset options, which can help us easily integrate other tools and libraries, such as Babel, TypeScript, ESLint, etc.
  • In addition to creating new projects, Vue CLI can also be used to manage existing Vue projects, providing various commands and options, such as building, testing, deploying, etc.
  • In general, Vue CLI is one of the essential tools in the Vue ecosystem, which can greatly improve our development efficiency.

Router view

  • Vue Router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build single-page applications. It can quickly help you build a single-page application, and based on the official API of Vue.js, it allows you to configure routing very conveniently.
  • Vue Router supports routing nesting and lazy loading of components, as well as a variety of navigation hooks, allowing you to better control routing jumps.

Vuex

  • Vuex state management library
    • Official documentation: https://vuex.vuejs.org/
    • Vuex Getting Started Tutorial: https://www.runoob.com/w3cnote/vuex-learn.html
    • Vuex combat: https://juejin.im/post/5c9f5b9e6fb9a05e3c6fdafe
  • Vuex helper library
    • Vuex-persistedstate:https://www.npmjs.com/package/vuex-persistedstate
    • Vuex-router-sync:https://www.npmjs.com/package/vuex-router-sync
  • Vuex case
    • Vuex shopping cart: https://github.com/bailicangdu/vue2-manage
    • Vuex e-commerce platform: https://github.com/one-pupil/Vue-Shop
    • Vuex music player: https://github.com/uncleLian/vue-music

View Test Utils

  • Vue Test Utils is a unit testing utility library officially provided by Vue.js, which can help us write and run test cases more easily and improve the quality and stability of our code.
  • Through Vue Test Utils, we can simulate user interaction behaviors, such as clicks, inputs, etc., to test the behavior and state of components.
  • Vue Test Utils also provides some auxiliary functions and tools, such as mount, shallowMount, etc., for creating and rendering component instances, which is convenient for us to test.
  • In addition to Vue Test Utils, there are also some third-party testing tool libraries, such as Jest, Mocha, etc., which can also be integrated with Vue.js to provide a more comprehensive testing solution.

Element UI

  • Element UI is a Vue 2.0-based desktop component library that provides rich components and diverse themes to help developers quickly build beautiful and easy-to-use interfaces.
  • Sample code:
<template>
  <el-button>默认按钮</el-button>
</template>

<script>
import { ElButton } from 'element-ui'

export default {
  components: {
    ElButton
  }
}
</script>

Vuetify

  • Vuetify is a Vue.js-based UI framework that provides rich components and styles to help developers quickly build beautiful web applications.
  • Vuetify fully follows the Material Design specification and provides a large number of Material Design-style components, such as buttons, cards, forms, dialog boxes, and more.
  • Vuetify also provides some advanced components, such as data tables, timelines, calendars, file uploads, etc., which can greatly improve development efficiency.
  • Vuetify also supports custom themes, which can easily customize the appearance of the application according to your own needs.
  • Vuetify's documentation is very detailed, providing rich examples and API documentation for developers to learn and use.

Ant Design Vue- Ant Design Vue: Ant Design Vue is a Vue.js-based UI component library developed by Ant Financial, which provides a series of commonly used UI components, such as buttons, forms, forms, pop-up windows, etc., which can Help developers quickly build beautiful and easy-to-use web applications. Ant Design Vue also provides rich theme customization functions, allowing developers to customize UI components that meet their own brand style according to their own needs.

6. Advantages and disadvantages of Vue

6.1 Advantages

Progressive framework, easy to learn and use

  • Progressive framework: Vue is a progressive framework that can be gradually introduced according to project requirements instead of introducing all functions at once, thereby improving the maintainability and scalability of the project.
  • Easy to learn and use: Vue's syntax is simple and easy to understand, with detailed documentation and easy to use. It is a very friendly framework for beginners.

Data-driven view to improve development efficiency

  • Data-driven view to improve development efficiency
    • Example: Vue associates data and views through data binding. You only need to pay attention to data changes, and the views will be automatically updated, which greatly improves development efficiency.

Component-based development, easy to maintain and reuse

  • Component-based development: Vue adopts a component-based development method to split the page into multiple components. Each component only focuses on its own logic and style, which improves the readability and maintainability of the code and facilitates the development of components. reuse.

  • Easy to maintain and reuse: Vue provides a wealth of APIs and plug-ins, allowing developers to quickly build reusable components and modules, while also facilitating project maintenance and upgrades.

Lightweight, fast loading - Lightweight: Vue.js only focuses on the view layer, so it is a lightweight framework. It's less bloated than Angular because it uses a virtual DOM, which renders views quickly and improves performance.

  • Fast loading: The file size of Vue.js is only around 20KB, so it loads and runs quickly. This makes Vue.js ideal for building single-page applications (SPAs).

6.2 Disadvantages

not SEO friendly

  • not SEO friendly

    Since Vue is rendered on the client side, and search engine crawlers only crawl HTML, the SEO of Vue is not as good as that of server-side rendered websites, and additional processing is required to improve the SEO effect.

Compared to React, the ecosystem is not perfect

  • Compared with React, the ecosystem is not perfect: Vue's ecosystem is not perfect compared to React, so there may be some inconveniences in some aspects. For example, in React, there are many mature third-party libraries that can be used, while Vue has relatively few third-party libraries, which requires developers to find solutions or write code to implement them by themselves.

For large applications, additional state management tools are required - For large applications, additional state management tools are required:

For example, Vuex is a state management library developed specifically for Vue.js applications. When the application becomes very large and complex, Vue.js may not be enough to handle all the state. In this case, you can use Vuex to manage the state of your application.

The above is the outline of Vue, I hope it can help you.

Guess you like

Origin blog.csdn.net/it_varlue/article/details/129951686