Vue. Js is introduced

Vue.js (pronounced vju/curliest) is a set of progressive frameworks for building user interfaces. Unlike other heavyweight frameworks, Vue is designed with bottom-up incremental development. Vue’s core library focuses only on the view layer and is very easy to learn and integrate with other libraries or existing projects. Vue, on the other hand, is fully capable of driving complex single-page applications developed with single-file components and libraries supported by the Vue ecosystem.

The goal of vue.js is to implement data binding and composite view components for responses through the simplest POSSIBLE API.

1. Technology selection — Why use vue.js?

  • Requirements: To implement an application for creating projects by selecting, inputting, and managing, viewing, editing projects. Multiple applications require bidirectional data binding
  • Experience: The user experience of Single Page application (SPA) is good, fast and close to the experience of native apps
  • Efficiency: provide common logic encapsulation implementation, high programming efficiency
  • Extension: Allows asynchronous loading of components and direct DOM manipulation (React requires refs to access specific DOM)
  • Lightweight: Lightweight frameworks with no aggressive apis, no dependency on containers, easy to configure, easy to use, and short startup time. Allow us to use the customary jquery.js/zepto.js at the same time

Second, project construction — Vue single file component blowing fresh wind

  • Directory structure:

    { "src":{ "app":{ "index":["index.html", "index.js", "index.less"] }, "Common" : [] / / js, the image of "components" : {" common ": [" cover. Vue", "loading. Vue", "toast. Vue]", "home" : / / general components [index. Vue, "Tab.vue ", "list.vue"],// page component //... // The single file component, like the HTML file, supports HTML, CSS, JS // but the home page entry should be regular HTML, JS}}}Copy the code
  • Modular:

    • The relationship between components and modules

      Answer by Jasin Yip @ Zhihu

    • Granularity of componentization: This project divides pages by folders and components by UI hierarchy and reuse relationships

  • summary

    The vUE single file component concentrates the structure, style and logic of a component into a single HTML-like file, which was previously done by the server side. Vue can be processed by JS, or by the specific module of the packaging tool.

    Such content concentration reduces the fragmentation of engineering projects and avoids frequent switching between HTML, CSS and JS files when writing a component in the programming process.

Code structure — An overview of Vue usage

  • Introduction to use

    1. Creating the root instance

      index.html

      <div id="app"></div>Copy the code

      index.js

      var app = new Vue().$mount('#app');Copy the code
    2. Create a single-file component

      demo.vue

      <template> <div>{{greeting}} world! </div> </template> <style> </style> <script> module.exports = { data: function(){ return { greeting: 'Hello' } } } </script>Copy the code
    3. Mount components

      index.js

      Var app = new vue ({components: {demo:}) var app = new vue ({components: {demo:}) demo } }).$mount('#app');Copy the code

      index.html

      <div id="app">
          <demo></demo>
      </div>Copy the code
    4. The results

      <div id="app"> <div>Hello world! </div> </div>Copy the code
  • Difficulties encountered in practice

    • Data bidirectional binding and monitoring changes:

      • Two-way data binding

        Two-way data binding refers to the ability to bind changes in object properties to changes in the user interface and vice versa

        Bidirectional: Data -> View, View -> Data

        Binding: When one content changes, another content changes with it

        Demo. vue: A typical two-way data binding example

        <template>
            <input type="text" v-bind:value="msg" v-on:input="changeMsg($event)"/>
            <div>{{msg}}</div>
        </template>
        <script>
            module.exports = {
                data: function(){
                    'msg':'hello'
                },
                methods: {
                    changeMsg: function(e){
                        this.msg = e.target.value
                    }
                }
            }
        </script>Copy the code

        Vue provides the V-model directive, which is abbreviated as follows

        Demo. vue: Example of the V-model instruction

        <template>
            <input type="text" v-model="msg"/>
            <div>{{msg}}</div>
        </template>
        <script>
            module.exports = {
                data: function(){
                    'msg':'hello'
                },
            }
        </script>Copy the code

        So far, to execute logic after data changes, you can extend the changeMsg content or listen for input and change events. Vue provides two ways to monitor change, computed and Watch

      • computed

        Demo. vue: computed example

        <template> <input type="text" v-model="msg"/> <div>{{msg}}</div> <div>{{rs}}</div> </template> <script> module.exports =  { computed: { rs: function () { console.log(this.msg) return this.msg.split('').reverse().join('') } } } </script>Copy the code
      • watch

        Demo. vue: Watch example

        <template> <input type="text" v-model="msg"/> <div>{{msg}}</div> <div>{{rs}}</div> </template> <script> module.exports =  { data:function () { return { msg: 'hello', rs: 'olleh' } }, watch: { msg: function (val) { console.log(val) this.rs = val.split('').reverse().join('') } }, } </script>Copy the code
      • Similarities and differences between computed and Watch

        1. The same

          Restricted by modern Javascript (and deprecated Object.Observe), Vue cannot detect additions or deletions of Object attributes

          They can only observe property changes that exist on Vue instance objects (in which this refers)

        2. different

          • Computed automatically adds attributes to Vue instance objects and overwrites existing attributes. Watch does not

          • Methods in computed execute only when they are accessed, not immediately when a listening property change occurs

            The method in Watch executes immediately when a change in the listening property occurs

            encountercomputedThe monitor is invalid, andwatchThat’s why it works

          • Computed only cares about the results of the calculation, and there is no limit to how many attributes change, and it can listen for the results of multiple attribute changes

            The result of the calculated property is cached, except for the recalculation of dependent reactive property changes.

            Watch only cares about the change of an attribute and executes the corresponding logic when it changes

    • Unidirectional data flow

      • Vue encapsulates only the means of communication from parent to child: Prop

        The props contains properties and methods passed in by the parent component, which are added to the instance object of the Vue component

      • Vue suggests a way to communicate from child to parent: custom events

        The parent component provides a custom event that receives information from the child component and executes the corresponding function

      • Communication between arbitrary components added by Vue: Global custom events (non-parent-child component communication)

        1. Set up a new Vue instance:

          var bus = new Vue()Copy the code
        2. * It is recommended to hang it on window to use window.Bus = Bus globally in projects

        3. Listen for custom events in component A

          A.vue

          <script>
              module.exports = {
                   created: function(){
                      bus.$on('event-A', function (something) {
                        // ...
                      })
                   }
              }
          </script>Copy the code
        4. Fires custom events in component B

          B.vue

          <script>
              module.exports = {
                   created: function(){
                      bus.$emit('event-A', 'say something')
                   }
              }
          </script>Copy the code
    • The life cycle

      • Basic graphic

      • The life cycle after joining Keep-Alive

        <template>
            <div id="parent">
                <keep-alive>
                    <component v-bind:is="nowChild"></component>
                </keep-alive>
            </div>
        </template>
        <script>
            var child1 = require('child1.vue')
            var child2 = require('child2.vue')
            module.exports = {
                data: function(){
                    return {
                        nowChild: 'child1'
                    }
                },
                components:{
                    child1: child1,
                    child2: child2
                }
            }
        </script>Copy the code

        The basic life cycle of the child component of keep-Alive is similar to that of the parent component of Keep-Alive. However, switching between the child components of Keep-Alive triggers activated and deactivated instead of triggering the basic life cycle of the child component twice

4. Experience Optimization — User experience for a single page app

  • Principle 1: avoid external chain jump

    Single-page applications provide a consistent, smooth user experience within a single page. However, the jump between single page and external chain will produce a lot of calculation, rendering, but exposed the shortcomings of single page application is not “lightweight”. Therefore, avoiding external link skipping and reducing the possibility of external link being clicked within a single page can help reduce users’ perception of obvious experience differences and improve user experience to a certain extent.

    There is a need to open the external chain directly, optimization measures can be opened in a new window.

  • Principle 2: Optimize the first screen

    This is especially true on the first screen. It takes a long time to enter a single page, which is similar to opening an APP. The first thing you see is the first screen picture, animation, guidance and advertisement.

    Optimization here also needs to start from both technical and view aspects. Technically, server-side rendering and asynchronous loading of components are used. In view, the first screen needs to change from blank to something as soon as possible.

  • Rule 3: Use caching

    Single-page apps can fully implement the MV* concept, and the update of the view reflects the update of the data. Time is spent in DOM rendering, logical operations, and waiting for requests to return, which can be cached for future use.

    The use of caching is a major factor in the convergence of the single-page app experience to native apps.