Vue Foundation (Data Request, Component, Attribute, etc.)

Posted by methodman on Thu, 22 Aug 2019 13:50:58 +0200

Vue Foundation (Data Request, Component, Attribute, etc.)

axios&&fetch

  • Purpose: To use data requests in frameworks

  • Data Request

    • Using fetch provided by native js

    • Using third-party encapsulation libraries: axios

      • axios can be mounted uniformly in Vue

      ​ Vue.prototype.$http = axios

    • fetch and axios

      • axios encapsulates XSRF layer on the data obtained
        • axios underlying automatically formats data
      • The fetch is not encapsulated. The fetch is the formatted data.
        • fetch is formatted in one more layer
          • res.json()
          • res.blob() formatted binary
          • res.text()
//Axios Summary npm i axios 
			//Or introducing cdn

//Unify the request header for axios post
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 

  Vue.prototype.$http = axios  //Mount axios

  new Vue({
    el: '#app',
    data: {
      list: []
    },
    methods: {
      static () {//Request static data without passing in data
          /* Request static data [simulated false data - mock data]
           *  			Copy similar field data online
           * 			Use third-party mock.js to generate json data [code to generate data]
           * 			esay mock Online website*/
        this.$http
          .get('./data/list.json')
          .then( res => {
            console.log( res )
            this.list = res.data.data.content
          })
          .catch( error => console.log( error ))
      },
      get () {//Request dynamic data, get method
        axios({
          url: 'http://localhost/get.php',
          params: { //This is the reference to the get request
            a: 5,
            b: 4
          }
        }).then( res => console.log( res ))
          .catch( error => console.log( error ))
      },
      post () {//Request dynamic data, post method
          /*
            The official npmjs method cannot be used directly
            Method: 1. Set the request header first. 
                 2. Instantiating the constructor function of URLSearchParams to get the params object
                 3. Data transmission using append method on params object

          */
        let params = new URLSearchParams()
        params.append('a',1)
        params.append('b',2)
        axios({
          url: 'http://localhost/post.php',
          method: 'post',
          data: params, headers: {  //Setting the request header for a single request (only one is needed for setting the request header in unison with the one above)
               'Content-Type': "application/x-www-form-urlencoded"
            }
        }).then( res => console.log( res ))
          .catch( error => console.log( error ))
      }
    }
  })
//fetch summary

 new Vue({
    el: '#app',
    data: {
      list: []
    },
    methods: {
      static () {//Getting static data
        fetch('./data/list.json')
          .then( res => res.json() ) //Format the obtained json data 
          .then( data => {
            this.list = data.data.content
          })
          .catch( error => console.log( error ))
      },
      get () {// get method for requesting dynamic data
        fetch('http://localhost/get.php?a=1&b=2')//The parameters of the request are written on the url
          .then( res => res.text() )//Data formatting res.json()/res.blob()
          .then( data => console.log( data ))
          .catch( error => console.log( error ))
      },
      post () {// post method for requesting dynamic data
        fetch('http://localhost/post.php',{
          method: 'POST',
          headers: new Headers({ //Setting the request header
            'Content-Type': 'application/x-www-form-urlencoded' // Specify submission as form submission
          }),
          body: new URLSearchParams([['a',1],['b',2]]).toString()
        }).then( res => res.text() )
          .then( data => console.log( data ))
          .catch( error => console.log( error ))
      }
    }
  })
  • axios and fetch requests return Promise objects, so use. then().catch(), but fetch needs to write two. then(), the first to format data.
  • History
    • Vue1.0
      • Vue 1.0 data requests we use a third-party encapsulation library called vue-resource
      • vue-resource is now obsolete, and its authors recommend that we use axios
        • vue-resource is used in the same way as axios
          • this.$http.get
          • this.$http.post
          • this.$http({})
          • vue-resource has jsonp method, but axios does not.
    • Vue2.0
      • axios [arguably the best encapsulation library for data requests at the moment]
      • fetch
  • The difference between ajax and fetch
    • fetch is based on promise and can be combined with async/await, which is simpler than ajax.
    • ajax is for MVC programming, not in line with the current front-end MVVM wave.
    • fetch only reports errors to network requests. 400,500 requests are considered successful and need to be encapsulated to process.
    • ajax requests success only when the status is 200 or 304.
    • The essence of Ajax is to request data using an XMLHttpRequest object
    • fetch has no way to monitor the progress of requests natively, while XHR can.
    • fetch is a method of global window.

Computational attributes

  <div id="app">
    <p> {{ msg }} </p>
    <p> Computational attributes: {{ newMsg }} </p>
  </div>
 
<script>
    new Vue({
        el: '#app',
        data: {
          msg: 'I love qiao daima !!!'
        },
        computed: {
          newMsg () {//Implementing Reverse
            return this.msg.split('').reverse().join('')
          }
        }
      })
</script>
  • Use:

    1. Define a computed attribute in the selection. The value of the attribute is an object. Storage in the object is a method. These methods must have return values.
    2. Within the scope of the vm instance, use this method name directly as a global variable
    3. Note that no () is added after the method name.
  • When to use: Logically, the instances are treated directly as global variables

Listening Attribute (watch)

  • watch is an option in Vue that monitors changes in data and performs some operations when the data changes.

    new Vue({
        el: '#app',
        data: {
          firstName: '',
          lastName: '',
          fullName: '',
          num: 0
        },
        watch: {
          firstName ( val ) {
            this.fullName = val + this.lastName
          },
          lastName ( val ) {
            this.fullName = this.firstName + val 
          },
          num: {
            deep: true, // Deep monitoring      
            handler ( val ) {
              //  The triggering method when num changes
              console.log( val )
            }
            // The delegate declared num in wacth and immediately executed the handler method
        	immediate: true
          }
        }
      })
    
  • Summary: methods vs computed vs Watch

  • How to use it in a project

      1. Event handlers:methods
      1. watch

        When there is a large amount of data interaction and asynchronous processing

      1. computed
        • Logical Processing
        • Use in V as a global variable

Mixing in

  • Mixed Forms
    • Global mixing [not recommended]
    • Local mixing
  • The role of mixing:
    • Separate one or more of the options from each other to make the functions more single and efficient, and conform to the idea of modularization.
<script src="./js/method.js"></script>
<script>
   /* 
    Global Inclusion
      All components will be added to the list of options. 
  Vue.mixin({
    methods: {
      bb () {
        alert('bb')
      }
    }
  })
   */
  new Vue({
    el: '#app',
    mixins: [ obj ]//Local mixing
  /* 
    Local mixing
      Introduce an object through the mixins option
  */
  })
</script>

assembly

  1. Start with a brief understanding of the history of front-end componentization

    • Front-end and back-end coupling
      • Front-end and back-end non-segregation projects
          1. Looking for Background to Build Project Development Environment
          1. Find the static resource directory in the project directory
            • js
            • img
            • css
          1. Synchronized modification of css
    • Front and back end separation
    • The emergence of front-end teamwork projects
      • Componentization to Solve Multi-Person Collaboration Conflict
      • multiplexing
  2. The concept of components

    • Component is an aggregate of html, css, js, img, etc.
  3. Components in Vue are extensible functions

    • Extended by Vue.extend()

      ƒ Vue (options) {//Vue
          if (!(this instanceof Vue)
             ) {
              warn('Vue is a constructor and should be called with the `new` keyword');
          }
          this._init(options);
      }
      ƒ VueComponent (options) {//Vue.extend()
          this._init(options);
      }
      
    • VueComponet is a constructor that we don't instantiate with new. We want components to be labeled.

      <Hello/> -->  <div></div>
      <Banner></Banner>
      
    • To legalize components, you must register for parsing

    • Registration of Components [Creation]

      • Global registration
      • Local registration
    Registration of components
    <body>
      <div id="app">
        <Hello></Hello>
        <Hello/>
      </div>
    </body>
    <script>
      // Global registration
        
      // Component options
      var Hello = Vue.extend({
        template: '<div> hello assembly </div>'
      })
      // Registration of components
      // Vue. component (component name, component option)
      Vue.component('Hello',Hello);
       /*  The effect is the same as that achieved above.
       Vue.component('Hello',{
        template: '<div> hello Component </div>'
      })
       */
      new Vue({
        el: '#app'
      })
    </script>
    
     <script>
      // Component Registration - Local Registration
      new Vue({
        el: '#app',
        components: {
          // Component Name: Component Options
          'Hello': {
            template: '<div> hello </div>'
          }
        }
      })
    </script>
    
  • Naming specification for components

     Vue.component('Hello',{         //<Hello></Hello>
        template: '<div> hello </div>'
      })
      Vue.component('HeaderTitle',{  // <header-title></header-title>
        template: '<div> HeaderTitle </div>'
      })
      Vue.component('movie-list',{   // <movie-list></movie-list>
        template: '<div> Movie List </div>'
      })
    
  • Use of components

    • There are some tags in html / h5, whose parent and child elements are specified. If we use components at this time, we will break this rule for so long, and then we will make mistakes.

    • This type of label includes:

      ​ ul li

      ​ ol li

      ​ dl dt dd

      ​ table tr td

      ​ selcet option

    • Solution: Binding a component with is attribute

    <body>
      <div id="app">
        <table border="1">
          <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
          <tr is = "Hello"></tr>
        </table>
      </div>
    </body>
    <script>
      Vue.component('Hello',{
        template: ` <tr>
                          <td>4</td>
                          <td>5</td>
                          <td>6</td>
                    </tr>`
      })
      new Vue({
        el: '#app'
      }) 
    </script>
    
    • Click on a switch to switch between two components
    <body>
      <div id="app">
       <button @click = " comp = comp === 'UserLogin'? 'PhoneLogin':'UserLogin'"> switch </button>
       <keep-alive> <!-- Dynamic Caching Component -->
        <component :is = "comp"></component>  <!-- Dynamic components -->
       </keep-alive>    
      </div>
    </body>
    <script>
     Vue.component('UserLogin',{
       template: '<div> User name password login </div>'
     })
     Vue.component('PhoneLogin',{
       template: '<div> Short Message Authentication Code Logon </div>'
     })
      new Vue({
        el: '#app',
        data: {
          comp: 'UserLogin'
        }
      }) 
    </script>
    
    • Template template
        1. The template tag is outside the scope of the instance template
        2. The template tag will not be parsed when it is outside, that is, it will appear in the dom structure. If it is placed in the scope of the instance, it will be parsed, it will not appear in the dom structure.
        3. There must be and only one direct child element in template
    <body>
        <div id="app">
            <Hello></Hello>
            <template>   <!-- template Labels are not displayed when placed in instances -->
          <p> Template template </p>
        </template>
        </div>
    
        <template id="hello-box">
        <!-- template There must be only one direct child element -->
        <div> Hello </div>
      	</template>
    </body>
    <script>
        Vue.component('Hello', {
            template: '#hello-box'
        })
        new Vue({
            el: '#app'
        })
    </script>
    
    • Component nesting
    <body>
      <div id="app">
        <Father></Father>
      </div>
    
      <template id="father">
        <div>
          <h3> Here is father assembly </h3>
          <Son></Son>  <!-- Use child components as tags in the template of parent components -->
        </div>
      </template>
    
      <template id="son">
        <div>
          <h4> Here are the subcomponents </h4>
        </div>
      </template>
    
    </body>
    <script>
      Vue.component('Father',{
        template: '#father'
      })
      Vue.component('Son',{
        template: '#son'
      })
    
      new Vue({
        el: '#app',
        data: {
          comp: 'UserLogin'
        }
      })
    </script>
    
    • Component Nesting - Local Form
    //The html section is the same as above
    new Vue({
        el: '#app',
        data: {
          comp: 'UserLogin'
        },
        components: {
          'Father': {
            template: '#father',
            components: {
              'Son': {
                template: '#son'
              }
            }
          }
        }
      })
    

Topics: Vue axios JSON Attribute