Brand Management Cases

Add a new brand

The code examples

Add () {// analyze: //1. Obtain id and name from data. Add this object to the list on the current data by calling the array method. Note: In Vue, we have implemented double data binding. Whenever we modify the data in data, Vue automatically listens to the data changes and applies the latest data to the page. By the time we realize the fourth step above, we are already getting started with Vue. We are more in the process of manipulating the Model data in the VM. At the same time, while manipulating the Model data, Var car = {id:this.id, name:this.name, ctime:new Date()} this.list.push(car) this.id = this.name = "} "var car = {id:this.id, name:this.name, ctime:new Date()} this.list.Copy the code

Delete the brand

The code examples

Del (id) {// Delete data by id // analysis: //1. Select * from index where id = 1; // this.list.some((item, I)=>{// if(item.id == id){// this.list.splice(I, 1) // // If return true, it immediately terminates subsequent loops of the array. Var index = this.list.findIndex(item => {if(item.id == id){this.list.splice(index, item.id == id){this.list.splice(index, item.id == id) 1) return true } }) }Copy the code

Select brands according to the criteria

1. 1. X version of the [] fiterBy instructions (https://cn.vuejs.org/api/#fiterBy), in (2) has been abolished in x 2. In 2 x version of realization of screening methods of manual [] (the ranking results show filter - https://cn.vuejs.org/v2/guide/list.html#Copy the code

The filter

Concept: Vue.js allows you to customize filters that can be used for some common text formatting. Filters can be used in two places: mustache interpolation and V-bind expressions. Filters should be added to the end of JavaScript expressions by “pipes”;

Private filter

  1. The HTML element
<td>{{item.ctime | dataFormat('yyyy-mm-dd')}}</td>
Copy the code
  1. privatefiltersDefine the way

The code examples

// Define a private filter
        var vm2 = new Vue({
            el: '#app2',
            data () {
                return {
                    dt: new Date()}},filters: {// Define a private filter. The filter has two conditions.
            If the name of the private filter is the same as that of the global filter, the private filter is called first
                dateFormat:function(dateStr, pattern = ""){
                    // Get a specific time based on the given time string
                    var dt = new Date(dateStr)

                    // yyyy-mm-dd
                    var y = dt.getFullYear()
                    var m = (dt.getMonth() + 1).toString().padStart(2.'0')
                    var d = (dt.getDate()).toString().padStart(2.'0')
                    // return y + '-' + m + '-' + d

                    if(pattern.toLowerCase() == 'yyyy-mm-dd') {return `${y}-${m}-${d}`
                    }else{
                        var hh = dt.getHours()
                        var mm = (dt.getMinutes()).toString().padStart(2.'0')
                        var ss = (dt.getSeconds()).toString().padStart(2.'0')


                        return `${y}-${m}-${d} ${hh}:${mm}:${ss}~ ~ ~ ~ `}}}})Copy the code

Using the new method String String ES6. Prototype. PadStart (maxLength, fillString = ‘ ‘) or String. Prototype. PadEnd (maxLength, FillString = “) to fill the string;

Global filter (code instance)

// Global filter for time formatting
        // Global filters are shared by all VM instances
        Vue.filter('dateFormat'.function(dataStr, pattern = ""){
            // Get a specific time based on the given time string
            var dt = new Date(dataStr)

            // yyyy-mm-dd
            var y = dt.getFullYear()
            var m = dt.getMonth() + 1
            var d = dt.getDate()
            // return y + '-' + m + '-' + d
            

            if(pattern.toLowerCase() == 'yyyy-mm-dd') {return `${y}-${m}-${d}`
            }else{
                var hh = dt.getHours()
                var mm = dt.getMinutes()
                var ss = dt.getSeconds()


                return `${y}-${m}-${d} ${hh}:${mm}:${ss}`}})Copy the code

Note: When there are local and global filters with the same name, the local filter is called using the proximity principle, that is, the local filter is called before the global filter

Key modifiers and custom keyboard modifiers

  1. Custom keyboard modifiers in x
Vue.directive('on').keyCode.f2 = 113;
Copy the code
  1. Custom keyboard modifier in x
  • throughVue.config.keycodes. name = key valueAliases for defining key modifiers:
       Vue.config.keyCodes.f2 = 113;
Copy the code
  • Use custom keystroke modifiers:
       <input type = "text" v-model = "name" @keyup.f2 = "add">
Copy the code

Custom instruction

Global custom instruction

  • Use vue.directive () to define global directives
  • Parameter 1: the name of the directive. Note that the directive name does not need to be preceded by a V – prefix when it is defined. However, it must be preceded by a V – prefix when it is called
  • Parameter 2: is an object that has some custom related functions that can perform related operations at a specific stage

The code examples

<input type="text" class="form-control" v-model="keywords" v-focus v-color="'blue'">
Copy the code
        Vue.directive('focus', {
            bind: function (el) {// Every time an instruction is bound to an element, the bind function is executed immediately, only once
                // Note: In each function, the first argument, always el, represents the element to which the instruction is bound. The el argument is a native JS object
                The focus method does not work when the element is not yet inserted into the DOM
                // An element can only get focus if it is inserted into the DOM
                // el.focus()
            },
            inserted: function (el) {// INSERTED Indicates that the inserted function is executed once, when the element is inserted into the DOM
                el.focus()
                // Actions related to the JS action are best performed in a INSERTED position to prevent the JS action from taking effect
            },
            updated: function (el) { // When a Vnode is updated, it may fire several times}})Copy the code

Custom private directives

The syntax structure is similar to custom private filters

Directives :{// Customize the private directive 'fontweight':{// Set the font thickness bind: Function (el, binding){el.style.fontWeight = binding. Value}}, // El.style. fontSize = parseInt(binding. Value) + 'px'}}Copy the code

Brand management cases all code examples


      
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
   <script src='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
   <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>
   <div id="app">


       <div class="panel panel-primary">
           <div class="panel-heading">
               <h3 class="panel-title">Add a brand</h3>
           </div>
           <div class="panel-body form-inline">
               <label>
                   Id:
                   <input type="text" class="form-control" v-model="id">
               </label>

               <label>
                   Name:
                   <input type="text" class="form-control" v-model="name" @keyup.enter="add">
               </label>

               <! In Vue, if you use event binding to specify a handler function for an element, you can pass the parameter to the function if you enclose the parentheses.
               <input type="button" value="Add" class="btn btn-primary" @click="add()">

               <label>Search name keyword:<! -- Note: all instructions in Vue are called with the beginning of v- -->
                   <input type="text" class="form-control" v-model="keywords" v-focus v-color="'blue'">
               </label>
           </div>
       </div>


       <table class="table table-bordered table-hover table-striped">
           <thead>
               <tr>
                   <th>Id</th>
                   <th>Name</th>
                   <th>Ctime</th>
                   <th>Operation</th>
               </tr>
           </thead>
           <tbody>
               <! Vfor = list; vfor = list;
               <! Now we have a custom search method and pass all the keywords to the search method as parameters.
               <! Save all the data that matches the search keyword into a new array by executing a for loop inside the search method.
               <tr v-for="item in search(keywords)" :key="item.id">
                   <td>{{item.id}}</td>
                   <td v-text="item.name"></td>
                   <td>{{item.ctime | dateFormat()}}</td>
                   <td><a href="" @click.prevent="del(item.id)">delete</td>
               </tr>
           </tbody>
       </table>
   </div>

   <div id="app2">
       <h3 v-color = "'pink'" v-fontweight = "900" v-fontsize = "50">{{dt | dateFormat}}</h3>
   </div>
   <script>
       // Global filter for time formatting
       // Global filters are shared by all VM instances
       Vue.filter('dateFormat'.function (dataStr, pattern = "") {
           // Get a specific time based on the given time string
           var dt = new Date(dataStr)

           // yyyy-mm-dd
           var y = dt.getFullYear()
           var m = dt.getMonth() + 1
           var d = dt.getDate()
           // return y + '-' + m + '-' + d


           if (pattern.toLowerCase() == 'yyyy-mm-dd') {
               return `${y}-${m}-${d}`
           } else {
               var hh = dt.getHours()
               var mm = dt.getMinutes()
               var ss = dt.getSeconds()


               return `${y}-${m}-${d} ${hh}:${mm}:${ss}`}})// Customize the global key modifier
       Vue.config.keyCodes.f2 = 113

       Use vue.directive () to define global directives
       // Where: parameter 1: the name of the directive. Note that in the definition, the name of the directive does not need to be prefixed with v-
       // However, the directive name must be prefixed with v- when called
       // Argument 2: is an object that has some custom related functions that can perform related operations at a specific stage
       Vue.directive('focus', {
           bind: function (el) {// Every time an instruction is bound to an element, the bind function is executed immediately, only once
               // Note: In each function, the first argument, always el, represents the element to which the instruction is bound. The el argument is a native JS object
               The focus method does not work when the element is not yet inserted into the DOM
               // An element can only get focus if it is inserted into the DOM
               // el.focus()
           },
           inserted: function (el) {// INSERTED Indicates that the inserted function is executed once, when the element is inserted into the DOM
               el.focus()
               // Actions related to the JS action are best performed in a INSERTED position to prevent the JS action from taking effect
           },
           updated: function (el) { // When a Vnode is updated, it may fire several times}})// A custom instruction to set the font color
       Vue.directive('color', {
           // style, as long as the directive binds to the element, whether or not the element is inserted into the page, the element must have an inline style
           // In the future, the element will be displayed on the page, and the browser's rendering engine will parse the style and apply it to the element
           bind: function(el, binding){
               el.style.color = binding.value
               // Style-related operations can generally be performed in BIND}})var vm = new Vue({
           el: '#app',
           data() {
               return {
                   list: [{id: 1.name: 'Mercedes'.ctime: new Date()}, {id: 2.name: 'BMW'.ctime: new Date()},].id: ' '.name: ' '.keywords: ' '}},methods: {
               add() {
                   / / analysis:
                   //1. Obtain id and name directly from data
                   //2. Organize an object
                   //3. Add this object to the list on the current data by calling the array method
                   //4. Note: In Vue, we have implemented double block binding for data. Whenever we modify the data in data,
                   // By default, Vue monitors data changes and automatically applies the latest data to pages
                   //5. When we realize the above step 4, we have already started Vue, we are more in the VM Model data operation,
                   // At the same time, the specified business logic operates when the Model data is manipulated
                   var car = { id: this.id, name: this.name, ctime: new Date()}this.list.push(car)
                   this.id = this.name = ' '
               },
               del(id) {// Delete data by id
                   / / analysis:
                   //1. How to find the index of the object to be dropped by id
                   //2. If the index is found, call the array splice method directly

                   1 / / method
                   // this.list.some((item, i)=>{
                   // if(item.id == id){
                   // this.list.splice(i, 1)
                   // // In the some method of the array, a return true immediately terminates subsequent loops of the array
                   // return true;
                   / /}
                   // })

                   2 / / method
                   var index = this.list.findIndex(item= > {
                       if (item.id == id) {
                           this.list.splice(index, 1)
                           return true
                       }
                   })
               },
               search(keywords) {// Search for data by keyword
                   // var newList = []
                   // this.list.forEach(item => {
                   // if(item.name.indexOf(keywords) ! = 1) {
                   // newList.push(item)
                   / /}
                   // });
                   // return newList

                   ForEach some filter findIndex these are new array methods
                   // Each item in the array is iterated over to perform related operations
                   return this.list.filter(item= > {
                       / / note: ES6, as a String provides a new method, called String. Prototype. Includes (' to contain the String ')
                       // Return true if contained, false otherwise
                       if (item.name.includes(keywords)) {
                           return item
                       }
                   })
                   // return newList}}});// How to customize a private filter ()
       var vm2 = new Vue({
           el: '#app2',
           data() {
               return {
                   dt: new Date()}},filters: {// Define a private filter. The filter has two conditions.
               If the name of the private filter is the same as that of the global filter, the private filter is called first
               dateFormat: function (dateStr, pattern = "") {
                   // Get a specific time based on the given time string
                   var dt = new Date(dateStr)

                   // yyyy-mm-dd
                   var y = dt.getFullYear()
                   var m = (dt.getMonth() + 1).toString().padStart(2.'0')
                   var d = (dt.getDate()).toString().padStart(2.'0')
                   // return y + '-' + m + '-' + d

                   if (pattern.toLowerCase() == 'yyyy-mm-dd') {
                       return `${y}-${m}-${d}`
                   } else {
                       var hh = dt.getHours()
                       var mm = (dt.getMinutes()).toString().padStart(2.'0')
                       var ss = (dt.getSeconds()).toString().padStart(2.'0')


                       return `${y}-${m}-${d} ${hh}:${mm}:${ss}~ ~ ~ ~ `}}},directives: {// Customize private directives
               'fontweight': {// Set the font size
                   bind: function(el, binding){
                       el.style.fontWeight = binding.value
                   }
               },
               'fontsize': function(el, binding){// Note that this function is equivalent to writing code into bind and update
                   el.style.fontSize = parseInt(binding.value) + 'px'}}})</script>
</body>

</html>
Copy the code

Vue instance lifecycle

  • What is the life cycle: From the time a Vue instance is created, run, and destroyed, there are always a variety of events, collectively called the life cycle!
  • Lifecycle hooks: Just an alias for lifecycle events;
  • Lifecycle hooks = lifecycle functions = lifecycle events
  • Main classification of life cycle functions:
    • Life cycle functions during creation:
      • BeforeCreate: The instance has just been created in memory and the data and methods properties have not been initialized
      • Created: Instances are created in memory, data and methods are created, and templates have not yet been compiled
      • BeforeMount: At this point the template is compiled but not mounted to the page
      • Mounted: A compiled template is mounted to a specified container
    • Runtime lifecycle functions:
      • BeforeUpdate: This function is executed before the status update, when the status value in data is the latest, but the data displayed on the interface is old because the DOM nodes have not yet been re-rendered
      • Updated: This function is called after the instance is updated, when the state values in data and the data displayed on the interface are updated and the interface is rerendered
    • Life cycle function during destruction
      • BeforeDestroy: Called before instance destruction, at this step, the instance is still fully available
      • Destoryed: called after the Vue instance is destroyed. After the call, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed.

The sample code


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
</head>

<body>
    <div id="app">
        <input type="button" value="Modified MSG" @click="msg = 'No'">
        <h3 id = "h3">{{msg}}</h3>
    </div>

    <script>
        var vm=new Vue({
            el:'#app',
            data () {
                return{
                    msg: 'ok'}},methods:{
                show () {
                    console.log('Execute show method')
                }
            },
            beforeCreate() {// This is the first lifecycle function we have encountered, indicating that it will be executed before the instance is fully created
                // console.log(this.msg)
                // this.show()
                // Note that when the beforeCreate life cycle function is executed, the data in data and methods are not initialized
            },
            created() {// This is the second lifecycle function encountered
                // console.log(this.msg)
                // this.show()
                // In created, data and methods are already initialized
                // If you want to call a method in methods or manipulate data in data, you can only do it in Created at first
            },
            beforeMount() {// This is the third lifecycle function encountered that indicates that the template has been edited in memory, but not yet rendered to the page
                // console.log(document.getElementById('h3').innerText)
                // When beforeMount is executed, the elements in the page are not really replaced, just some template strings that were written before
            },
            mounted() {// This is the fourth lifecycle function encountered, indicating that the template in memory has actually been mounted to the page and the user can see the rendered page
                // console.log(document.getElementById('h3').innerText)
                // Mounted is the last life cycle function to create an instance. When mounted is executed, the instance is completed.
                // At this point, if nothing else is done, the instance just sits in our memory, motionless
            },

            // Next are the two events in the run
            beforeUpdate() {// The interface has not been updated yet.
                // console.log(' Contents of elements in interface: '+ document.getelementById ('h3').innertext)
                // console.log('data in MSG data is: '+ this.msg)
                BeforeUpdate, the data displayed in the page is still old, the data is up to date, the page is not in sync with the latest data
            },
            updated() {
                console.log('Contents of elements on the interface:' + document.getElementById('h3').innerText)
                console.log(The MSG data in 'data 'is: + this.msg)
                // The updated event executes when the page and data are in sync}});</script>
</body>

</html>
Copy the code

Vue-resource implements GET, POST, and JSONP requests

In addition to vue-Resource, you can also use axios’s third-party packages to implement requests for data

  1. In the previous study, how to initiate data request?
  2. Common data request types? get post jsonp
  3. Test URL request resource address:
    • Access interface: www.liulongbin.top:3005/api/getprod…
    • Add an interface: www.liulongbin.top:3005/api/addprod…
    • Delete the interface: www.liulongbin.top:3005/api/delprod…” + id
  4. Implementation principle of JSONP
    • Due to security restrictions of browsers, AJAX is not allowed to access data interfaces with different protocols, domain names, and port numbers. Therefore, browsers consider such access insecure.
    • You can dynamically create a script tag and point the attributes of the script tag to the address of the data interface. Because there is no cross-domain restriction on script tags, this method of data acquisition is called JSONP(note: JSONP only supports Get requests).
    • Specific implementation process:
      • Now the client defines a callback method that pre-defines operations on the data;
      • The name of the callback method is then submitted to the server’s data interface as a URL parameter
      • The server data interface organizes the data to be sent to the client, takes the name of the callback method passed by the client, concatenates a string that calls the method, and sends it to the client to parse and execute.
      • The client takes the string returned by the server and parses it as a script to get the JSONP data

The code examples


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
    <! Vue --> vue --> vue --> vue
    <! -- this.$http -->
    <script src="https://cdn.bootcss.com/vue-resource/1.5.1/vue-resource.min.js"></script>
    <! -- < script SRC = "https://cdn.jsdelivr.net/npm/[email protected]" > < / script > -- >
</head>

<body>
    <div id="app">
        <input type="button" value="Get request" @click="getInfo">
        <input type="button" value="Post request" @click="postInfo">
        <input type="button" value="The json request" @click="jsonpInfo">
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data() {
                return{}},methods: {
                getInfo() {// Send the get request
                    // After a GET request is initiated, the successful callback function is set through.then
                    this.$http.get('http://www.liulongbin.top:3005/api/getprodlist').then(response= > {
                        console.log(response)
                        // Retrieve the requested data from the server via result.body
                    })
                },
                postInfo() {// Initiate a POST request Application/x-www-form-urlencoded
                    // Manually initiated POST requests do not have a form format by default, so some servers cannot process them
                    // The third argument to the POST method, {emulateJSON: true}, sets the submitted content type to a normal form data format
                    this.$http.post('http://www.liulongbin.top:3005/api/addproduct', {}, { emulateJSON: true }).then(result= > {
                        console.log(result.body)
                    })
                },
                jsonpInfo(){// Initiate a JSONP request
                    this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result= > {
                        console.log(result.body)
                    })
                }
            }
        });
    </script>
</body>

</html>
Copy the code