Vue syntax finishing

Introduction to Vue


Vue is a progressive framework for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue's core library only focuses on the view layer, which is not only easy to use, but also easy to integrate with third-party libraries or existing projects.

Vue features
1. Follow the MVVM pattern

2. Simple coding, small size, high operating efficiency, suitable for mobile/PC development

3. It only focuses on UI itself, and can also introduce other third-party library development projects

3. The basic use of Vue
el: mount

data: model data

msg: data
 

Basic use of vue

</head>

<body>

    <div id="app">

        <p>{ {msg}}</p>

    </div>

    <div id="add">

        <p>{ {msg}}</p>

    </div>

<!--Import vue.js-->>

<script src="./vue.js"></script>

<script>

    //Instantiate a vue

    new View({

        the:'#app',

        data:{

            msg:'xxx'

        }

    })

</script>

</body>

</html>

Use of v-show

</head>

<body>

    <div id="app">

        <div v-show="money>=1000"> Eat hot pot</div>

        <div v-show="money>=2000">Haidilao</div>

        <div v-show="money>=500">饭</div>

        <div v-show="money<500">滚</div>

      <hr>

       <!-- Double branch -->

       <div v-show="age>=18">bar</div>

       <div v-show="age<18">Pick up trash</div>

</div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                money:1500,

                age:25

            }

        })

    </script>

</body>

<body>

    <!-- Both v-show and v-if can be used to control the display and hiding of labels

     <label v-show='Boolean'></label>

     <label v-if='boolean'></label>

    When the boolean value is true, they are shown: when the boolean value is false, they are hidden. -->

   

    <div id="app">

        <div v-show="display">I am controlled by v-show</div>

         <div v-if="display">I am controlled by v-if</div>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

             display:ture

            }

        })

         

    </script>

    <!-- interview questions

    v-show

    The essence is that the label display is set to none, and the control is hidden. Just switch based on css.

     v-show has a higher initial render cost.

     v-show is suitable for frequent switching effects.

   

     v-if

      Dynamically add or remove DOM elements to the DOM tree.

      v-if has a higher switching cost.

      v-if is suitable for situations where the operating conditions rarely change. -->

</body>

</html>

v-on

</head>

<body>

    <div id ="app">

<button v-on:click="fn1">Click me</button>

<button v-on:dblclick="fn2">666</button>

<button v-on:mouseenter="fn3">咦~</button>

    </div>

    <script src ="./vue.js"></script>

    <script>

        new View({

            the:'#app',

//Where to put the method in vue

methods:{

    fn1(){

        alert('Why')

    },

    fn2(){/

        alert('what's wrong')

    },

    fn3(){

    alert('I'm bored to death')

    },

}

        })

    </script>

</body>

</html>

v-model

<body>

    <div id="app">

        <input type="text" v-model="msg">

        <p>{ {msg}}</p>

        <select v-model="fruit">

            <option value="apple">苹果</option>

            <option value="orange">橘子</option>

            <option value="banana">香蕉</option>

        </select>

        <input type="checkbox" v-model="chk">

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the : '#app',

            data :{

            msg:'',

            fruit:'',

            chk:ture

            }

           

        })

    </script>

</body>

</html>

v-if

<body>

    <div id="app">

        <div v-if="money>=1000"> Eat hot pot</div>

        <div v-else-if="money>=2000">Haidilao</div>

        <div v-else-if="money>=500">饭</div>

        <div v-else>滚</div>

      <hr>

       <!-- Double branch -->

       <div v-if="age>=18">酒吧</div>

       <div v-else>Pick up trash</div>



 

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                money:1500,

                age:25

            }

        })

    </script>

</body>

</html>

The role of key in v-for

<body>

   <div id="app">

    <button @click="list.splice(1,0,{id:4,name:'yy'})">添加</button>

    <ul>

        <li v-for="item in list":key="item.index">

            <input type="checkbox">

            <span>{ {item.name}}</span>

        </li>

    </ul>

    <!-- Phenomenon: When I ticked rr, and then added yy at the position of subscript 1, it turned out that yy was ticked, and rr didn’t tick it.

         Reason: v-for will try to maximize the reuse of the current element, resulting in disordered state binding.

         Solution: Add a key attribute after v-for, and the key binds the unique value of this data (usually id, not string and number types)

     -->

   </div>

   <script src="./vue.js"></script>

   <script>

    new View({

        the:'#app',

        data:{

            list:[

                {id:1,name:'ww'},

                {id:2,name:'rr'},

                {id:3,name:'tt'},

            ]

        }

    })

   </script>

</body>

</html>

v-for iterates through the array

<body>

   

<!-- Syntax: <label v-for='item in array'></label> -->

<!-- [Original writing]

 for (let i = 0 ; i < list.length; i ++){

 let li = document.createElement('li')

 li.innerHTML = list[i]

 ul.appendChild(li)  -->

        <div id="app">

        <button @click="add">Add an element at the end</button>

        <ul>

            <!-- The first parameter is the element, and the second parameter is the subscript. Nothing to do with the name. -->

<!-- Most of the time, it is just to get the element, and the subscript may not be used. -->

            <li v-for="(item,index) in list">{ {index}}-{ {item}}</li>

        </ul>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                list:['aa','ss','dd','ff']

            },

            methods:{

                add(){

                    this.list.push('aa')

                }

            }

        })

    </script>

</body>

</html>

v-for iterates over numbers

<body>

    <div id="app">

        <ul>

            <!-- The specified number of loops

            num is 1 to 99 -->

            <li v-for="num in 99">{ {num}}</li>

        </ul>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app'

        })

    </script>

</body>

</html>

v-for traverses objects

<body>

        <!-- v-for can traverse objects

       Syntax: <label v-for="(val,key)in object"></label>

       <label v-for="val in object"></label> -->

    <div id="app">

        <ul>

             <!-- There are as many such tags as there are properties of the object. -->

            <li v-for="item in obj"> { {item}}</li>

            <hr>

             <!-- The first parameter is the attribute value, and the second parameter is the attribute name. -->

             <!-- It has nothing to do with the name, and it can also be abbreviated to only take the attribute value. -->

            <li v-for="(val,key) in obj">{ {val}}-{ {key}}</li>

        </ul>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                obj:{

                    name:'Xiao Huang',

                    age:'88',

                    sex:'man'

                }

            }

        })

    </script>

</body>

</html>

v-bind

<body>

<!-- Let inline attributes not be hardcoded -->

    <div id="app">

        <a href="http://www.baidu.com">Jump</a>

        <a v-bind:href="url">Jump</a>

        <button @click="change" target="_blank">跳转</button>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                url:'http://www.taobao.com'

            },

            methods:{

                change(){

                    this.url='http://www.mi.com'

                }

            }

        })

    </script>

</body>

</html>

cookie

 <!-- 【cookie】

One: Usage scenario:

1: Remember the password and log in automatically next time.

2: Record user browsing data and recommend products (advertisements).

Two: Features:

1: The cookie is saved on the browser side.

2: The data saved by a single cookie cannot exceed 4KB.

3: The data in the cookie is distinguished in the form of a domain name.

4: The data in the cookie has an expiration time, and the data will be automatically deleted by the browser after the expiration time.

5: The data in the cookie will be automatically sent to the server with the request.

three:

Due to the many shortcomings of the cookie storage mechanism, HTML5 no longer uses it, and instead uses the improved WebStorage storage mechanism.

(localStorage和sessionStorage) -->

event object

<body>

    <div id="app">

     <button @click="click">单击</button>

     <button @dblclick="dblclick">双击</button>

     <input type="text" placeholder="内容" @blur="blurText" @focus="focusText" @keydown="keydownText" @keyup="keyupText" @input="inputText">

    </div>

    <script src="./vue.js"></script>

    <script>

        // load event: triggered after the entire page is loaded

        // window.onload = function(){

        // alert("page loaded complete")

        // }

        new View({

            the:'#app',

            methods:{

                 click(){

                    alert('Xiao Lu's love brain');

                 },

                 dblclick(){

                    alert('Xiao Huang took an ugly photo of Xiao Zou sleeping');

                 },

                 blurText(){

                    console.log("blur event out of focus");

                 },

                 focusText(){

                    console.log("focus event acquisition");

                 },

                 keydownText(){

                    console.log("hot pot");

                 },

                 keyupText(){

                    console.log("pot");

                 },

                 inputText(){

                    console.log("ok");

                 }

            }

        })

    </script>

</body>

</html>

life cycle

<body>

   <div id="example">{ {message}}</div>

   <script src="./vue.js"></script>

   <script>

    var vm = new Vue({

        the :'#example',

        data:{

            message:'match'

        },

        beforeCreate(){

            console.log('beforeCreate');

        },

        created(){

            console.log('cresated');

        },

        beforeMount(){

            console.log('beforeMount');

        },

        mounted(){

            console.log('mounted');

        },

        beforeUpdate(){

            console.log('beforeUpdate');

        },

        updated(){

            console.log('updated');

            // After the component is updated, call the $destroyed function to destroy it

            //this.$destory();

        },

        beforeDestroy(){

            console.log('beforeDestroy');

        },

        destroyed(){

            console.log('destroyed');

        },

    })

   </script>

</body>

</html>

calculate exchange rate

<body>

    <div id="app">

        <p class="title">Exchange Rate Calculator</p>

        <ul>

            <li>

                <span>{ {from.currency}}</span>

                <input v-model="from.amount"></input>

            </li>

           <li v-for="item in to" v-bind:data-currency="item.currency" v-on:click="changeCurrency">

           <span>{ {item.currency}}</span>

           <span>{ {item.amount}}</span>

           </li>

        </ul>

        <p class="intro">Mouse click to switch currency types</p>

    </div>

    <script src="./vue.js"></script>

    <script>

        let rate={

            CNY:{CNY:1     ,JPY:16.876, HKD:1.1870, USD:0.1526, EUR:0.1294},

            JPY:{CNY:0.0595,JPY:1 ,HKD:0.0702, USD:0.0090, EUR:0.0077     },

            HKD:{CNY:0.8463, JPY:14.226,HKD:1, USD:0.1286, EUR: 0.10952   },

            USD:{CNY:6.5813, JPY:110.62, HKD:7.7759, USD:1, EUR:0.85164   },

            EUR:{CNY:7.7278, JPY:129.89, HKD:9.1304, USD:1.1742, EUR:1    },

        }

        let vm = new Vue({

            the:'#app',

            data:{

                from:{currency:'CNY',amount:100},

                to:[

                    {currency:'JPY',amount:0},

                    {currency:'HKD',amount:0},

                    {currency:'USD',amount:0},

                    {currency:'EUR',amount:0},

                ]

            },

            methods:{

                exchange(from, amount, to){

                    return(amount * rate[from][to]).toFixed(2)

                },

                changeCurrency(event){

                    const c = event.currentTarget.dataset.currency;

                    const f = this.from.currency;

                    this.from.currency= c;

                    this.to.find(_ => _.currency === c).currency = f;

                }

            },

            watch:{

                from:{

                    handler(value){

                        this.to.forEach(item => {

                            item.amount = this.exchange(this.from.currency,

                            this.from.amount, item.currency)

                        });

                    },

                    deep:true,

                    immediate:true

                }

            }

        })

    </script>

</body>

</html>

counter

<body>

    <script src="./vue.js"></script>

    <div id="app">

        <button @click="sub">-</button>

        <span v-text="num"></span>

        <button @click="add">+</button>

    </div>

    <script>

        new View({

            el:"#app",

            data:{

                num:1

            },

            methods:{

                sub:function(){

                    if(this.num>0){

                    this.num--;

                }else{

                    alert("Already the smallest");

                }

                },

                add:function(){

                if(this.num<20){

                    this.num++;

                }else{

                    alert("to reach the upper limit")

                }

            }

        }

    })

    </script>

</body>

</html>

Bind the style attribute

Bind class attribute in object mode

 <title>Document</title>

    <style>

        .box {

              width: 300px;

              height: 300px;

              border: 10px solid yellowgreen;

        }

        .bg{

            background-color: cornflowerblue;

        }

    </style>

</head>

<body>

    <div id="app">

        <button @click="btn">here</button>

        <!-- If you want to dynamically set the class, it is also for an object -->

        <!-- Attribute value: is the class name -->

        <!-- Attribute value: Boolean value, if it is true, it means there is this class name: false means no -->

        <!-- <div class="box" v-bind:class="{bg:ture}"></div> -->

        <!-- Convert the Boolean value into a variable name, and clarify this variable in data -->

        <div class="box" v-bind:class="{bg:isBg}"></div>

    </div>

    <script src="../vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                isBg:true,

                flag:0

            },

            methods:{

                btn(){

                    if(this.flag==0){

                        this.isBg=true

                        this.flag=1;

                    }

                    else{

                        this .isBg=false;

                        this.flag=0;

                    }

                }

            }

        })

    </script>

</body>

</html>

Bind the style property as an object

 <title>Document</title>

</head>

<body>

    <div id="app">

        <!-- Write styles in inline attributes -->

        <div style="color:royalblue ; font-size: 48px;">Huang Suirui is so handsome</div>

   

        <!-- Transform the inline attribute into an object, and bind the style attribute in an object way

        Add {} to the outside; change the attribute value to a string; change the height to a comma; change the attribute name to the object name -->

        <div v-bind:style="{color:'red',fontSize:'48px'}">Xiao Zhong is shameless</div>

               <!-- Change the attribute value to a variable -->

               <!-- The first color is the style name, the second color is the variable name, consistent with the variables in data -->

        <div v-bind:style="{color:color,fontSize:size}">Xiao Zou is useless</div>

    <script src="../vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                color:'red',

               size:'24px'

           

           

            }

        })

    </script>

</body>

</html>

computed property

Computed property basic structure

<body>

    <!-- computed property

 You can write some attributes of calculation logic in it.

 He does not directly return the result like ordinary functions, but returns the result after a series of calculations.

 At the same time, as long as a certain attribute in data is applied to it, when this attribute changes, the calculated attribute can sniff this change and execute it automatically

 Definition: The attribute to be used does not exist, and it is calculated from the existing attributes.

Use: Define the calculated property in the computed object, and use { {method name}} to display the calculated result  on the page . -->

 <script>

    //basic structure

    new View({

        he:'',

        //data

        data:{},

        // method attribute

        // Event binding, no return, no cache

        methods:{},

        // listener (respect structure)

        // Listen for a value change without returning a value

        watch:{

                data to listen to (){}

        },

        // computed properties (result-focused)

        // There must be a return, only the result is required, and there is a cache

        copputed:{

            computed property name() {

                // After a series of calculations

                return the result after processing the operation

            }

        }

    })

 </script>

 <!-- Cache properties of computed properties

 When the computed property is called for the first time, a result will be generated, and the result will be cached, and each subsequent use of this property will be taken from the cache.

 When its dependencies change, it will recalculate to get a result, and then cache it. -->

</body>

</html>

Basic use of computed properties

<body>

    <div id="app">

        <p>Original string: { { message }}</p>

        <p>Calculate the reversed string: { {·reverseMessage·}}</p>

        <p>Convert the original string to lowercase: { { toLowerCase}}</p >

        </div>

       

        <script src="../vue.js"></script>

        <script>

        new View({

        the:'#app',

         data:{

        message:'ABCDEFG'

         },

        computed:{

        // Compute the reversed string

        reverseMessage:function(){

        // split() splits a string into an array of strings

        // reverse() reverses the order of the elements in the array

        // join() converts all elements in the array to a string

        return this.message.split('').reverse().join('')

    },

    //Convert the original string to lowercase

    toLowerCase(){

        //substring(from,to) extracts characters between two specified subscripts in the string

        //toLowerCase() is used to convert a string to a trumpet

        return this.message.substring(0,7).toLowerCase

    }

}

        })

        </script>

</body>

</html>

The full structure of computed properties

<body>

    <!-- 1. Each computed property contains a getter function and a setter function.

    2. The computed property will use the getter function by default, and the setter function is not common, so the general computed property getter and setter are not written.

    3. The getter function is the default usage, but the setter function is not the default usage. If you want to use a setter function, you must manually write out the setter function.

    4. The formal parameter in the setter function is the value you want to modify -->

<!-- Prepare a container -->

<div id="app">

姓:<input type="text" v-model="lastName"> <br><br>

名:<input type="text" v-model="firstName"> <br><br>

Full Name: <span>{ { fullNamel}</span> <br><br>

<button @click="btn">Modify the value of the computed property</button>

</div>

<!-- Import Vue -->

<script src="../vue.js"></script>

<script>

new View({

the:'#app',

 data(){

return {

firstName:'Tutu',

lastName:'Hu'

}

},

computed:{

fullName: {

// get: Triggered when the value is obtained

// When someone reads ful1Name, get will be called, and the return value will be used as the value of fullName.

 get(){

return this.firstName +'_' +this.lastName;

},

//set; trigger when the value is set

//When the computed property is modified, call set

set(value){

    console.log('set',value);

    const arr = value.split('-')

    this.firstName = arr[0]

    this.lastName = arr[1]

}

}

},

methods:{

    btn(){

        this.fullName = 'Hu Yingjun'

    }

}

})

</script>

</body>

</html>

Complete Structure of Computed Properties 2

<body>

    <script>

        // 1. Declaration string

let str = 'The Center of the Universe - Jiangxi Software Vocational and Technical University';

let str1 = "The center of the universe - Jiangxi Software Vocational and Technical University";

let str10 = 'The center of the universe - Jiangxi Software Vocational and Technical University';

// 2. Determine whether a string is in a string

let index1 = str.index0f('universe')

console.log(index1);//0

// 3. Intercept the string (the first parameter: which subscript to start intercepting; the second parameter: the length of the interception.

 let str2 = str.substr(7,2)

 console.log(str2); // Jiangxi

// 4. Modify the string (the first parameter: the string to be modified; the second parameter: the modified string.

let str3 = str.replace("Universe","Internet")

console.log(str3);// The center of the Internet--Jiangxi Software Vocational and Technical University

// 5. Split the string

let str4 = "23"

// This function must return an array

let array = str4.split(',')

// is the delimiter, when the delimiter is found, it is removed from the string and an array of substrings is returned.

// If the delimiter is not found or omitted, the array contains one element consisting of the entire string.

// If the delimiter is an empty string, convert str to a character array

console.log(array); //['Scatter', "Lang'," Hey', 'Yo']

// 6. Case conversion (only English has case, Chinese does not exist)

console.log('ABCDEF'.toLowerCase());// convert to lowercase abcdef

console.log('abcdef'.toUpperCase());// convert to uppercase ABCDEF

console.log('Case does not exist in Chinese'.toLowerCase);

    </script>

</body>

</html>

event modifier

event method

 <!-- [event method]

@click: When the element is clicked, the click event occurs.

@dbclick: When the element is double-clicked, the dbclick event occurs.

@focus: The focus event occurs when an element gains focus.

@blur: The blur event occurs when the element loses focus.

@submit: When the form is submitted, the submit event occurs.

@keydown: When the keyboard is pressed, the keydown event occurs.

@keyup: When the keyboard is released, the keyups event occurs.

@mouse enter: When the mouse pointer passes through (enters) the selected element, a mousedown event occurs.

@mouse down: When the mouse pointer moves over the element and the left mouse button is pressed, a mousedown event occurs.

@mouse leave: When the mouse leaves the selected element, the mouseleave event occurs.

@mouse move: The mousemove event occurs when the mouse pointer moves within the specified element.

@mouse out: Fired when the mouse pointer leaves the selected element or any child elements.

@mouse over: The mouseover event occurs when the mouse pointer is over the element.

@mouse up: The mouseup event occurs when the mouse pointer moves over the element and the left mouse button is released. -->




 

   <!-- [event]    

  Events in JavaScript can be understood as an interactive operation that occurs in HTML documents or browsers, making web pages interactive.

  The common ones are loading events and mouse events.

 【Event flow】

 Since DOM is a tree structure, if events are bound to parent-child nodes and child nodes are triggered, there is a sequence problem, which involves event flow.

  When a page triggers an event, it will respond to the event in a certain order, and the event response process is an event flow.

[Three stages of js event flow]

 Event capture phase (capture phrase): the event starts to be triggered by the top-level object, and then propagates down step by step until the target element;

 In the target phase (target phrase): on the element where the event is bound;

 Event bubbling phase (bubbling phrase): The event is first received by specific elements, and then propagated up step by step until non-specific elements;

 (Event capture is from top to bottom, while event bubbling is from bottom to top.) -->


 

<div id="app">

    <!-- When this button is clicked, the fn1 function is called -->

    <button v-on:click="fn1">Click me</button>

    <!-- When the button is double-clicked, the fn1 function is called -->

    <button v-on:dblclick="fn1">双击666</button>

    <!-- When this button is moved, call the fn2 function -->

    <button v-on:mouseenter="fn2">Move into me</button>

    <!-- Shorthand form: change v-on: to @ is the shorthand form -->

    <h4>The following is the abbreviation</h4><hr>

    <!-- When this button is clicked, the fn1 function is called -->

    <button @click="fn1">click me</button>

    <!-- When the button is double-clicked, the fn1 function is called -->

    <button @dblclick="fn1">Double click 666</button>

    <!-- When this button is moved, call the fn2 function -->

    <button @mouseenter="fn2">Move into me</button>

</div>

    <script src="./vue.js"></script>

    <script>

    new View({

    the: '#app',

    //Where to put the method in Vue

    methods:{

    fn1(){

    alert('Click me to do it?')

},

    fn2(){

    alert('Do you want to do it?')

    }

    }

    })

    </script>

</body>

</html>

event bubbling

<body>

    <div id="outer" @click="">

        <button @click="click"> click me </button>

    </div>

    <script>

        // Event bubbling and event capture were respectively proposed by Microsoft and Netscape to solve the problem of event flow (order of events) in the page.

        // event bubbling:

        // Microsoft proposed an event stream called event bubbling.

        // Event bubbling can be compared to putting a stone into the water, and the bubbles will always emerge from the bottom of the water.

        // That is to say, the event will start from the innermost element and propagate upward until the document object.

        // Therefore, under the concept of event bubbling, the order of click events on button buttons should be button→div→body→html→document.

        // Event capture:

        // Netscape proposed another event stream called event capturing (event capturing). 11 Contrary to event bubbling, events will occur from the outermost layer until specific elements.

        // Therefore, under the concept of event capture, the order in which the click event occurs on the button button should be document→html→bodv→div→button.

        // Later, W3C adopted a compromise method to quell the war between Netscape and Microsoft, and formulated a unified standard-first capture and bubbling.

    </script>

</body>

</html>

Introduction to event modifiers

<body>

    <!-- event modifier

     

    event.preventDefault()/prevent default behavior or event.stopPropogation()/prevent event bubbling.

    The above methods need to deal with the details of DOM events, and the code is cumbersome.

    To solve this problem, Vue.js provides event modifiers.

    Modifiers are denoted by directive suffixes beginning with a dot. -->

 <!-- stop prevents bubbling events from continuing to propagate -->

  a v-on:click.stop="doThis"></ a>

<!-- .self When the event target is the current element itself, trigger the event -->

<ul @click.self="ulclick"></ul>

<!-- .capture changes the original default bubbling method to capture method -->

<!-- .prevent prevent event default behavior -->

<!-- @submit.prevent submit event no longer reloads the page -->

<form v-on:submit.prevent="onSubmit"></form>

<!-- .stop.prevent modifiers can be chained to prevent both bubbling and the default behavior. -->

<a v-on:click.stop.prevent="doThat"></ a>

<!-- Modifiers only -->

<form v-on:submit.prevent></form>

</body>

</html>

listener

Listener basic structure

<script>

        // [listener]

        // Function: Used to monitor whether the data has changed, and call the function once there is a change.

        // Syntax: Write a watch at the same level as data and methods

         new View({

        he:'',

        data:{},

         methods:{},

         // listener

         watch:{

        // Parameter one: the changed value.

        // Parameter two: the value before the change.

        Data to listen to (newValue, oldValvue) {

        }

        }

        })

        </script>

The base of the listener belongs to

<body>

    <div id="app">

        <button @click="msg='hahahahaha'">Modify the value of msg</button>

        <p>{ {msg}}</p>

     </div>

    <script src="./vue.js"> </script>

    <script>

        new View({

            the:'#app',

            data:{

                msg: 'quack quack quack'

            },

            //Where to write the listener

            watch:{

                // listener for data changes

                // Basic data type, these two parameters are meaningful

                msg(newValue,oldValue){

                    // After listening to the data change, the behavior that needs to be completed

                    console.log('data changed', newValue, oldValue);

                }

            }

        })

    </script>

</body>

Use of listeners in arrays

<body>

    <div id="app">

     <ul>

        <li v-for="item in list">{ {item}}</li>

     </ul>

     <button @click="list.push('Pleasant Goat')">Add an item</button>

    </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                list:['Xiao Huang is very useless','Xiao Zhong has a lot of things','Xiao Lu's love brain']

            },

            watch:{

                list(newValue,oldVaule){

                    console.log('data changed', newValue, oldVaule,);

                }

            }

        })

    </script>

   

</body>

[Listen to the array]

Arrays are application types, and there are more complex listening rules.

In theory, modifying the contents of an array, such as modifying the value of an element in the array, or adding new elements to the array, will not modify the address of the array itself.

For this reason, Vue.is has made special treatment for the array, so that the modifications made to the array using the standard array operation method can be intercepted.

1. Vue cannot detect changes in the following arrays:

a. When you use the index value to directly set an array, for example: vm.items[index0fItem] = newValue

b. When you modify the length of the array, for example: vm.items.length = newlength

2. Using standard methods to modify the array can be listened to

https://v2.cn.vueis.org/v2/guide/list.html#%E6%95%B0%E7%BB%84%E6%9B%B4%E6%96%B0%E6%A3%80 %E6%B5%8B push() add at the end pop() delete at the end

unshift() head added

shift() head delete

splice() delete, add, replace

sort()Sort

reverse() reverse order

(Vue wraps the change method of the monitored array, so they will also trigger the view update, the above is the wrapped method.) -->

<body>

    <div id="app">

        <button @click="list.pop()">Delete an item</button>

        <button @click="list.push('Pleasant Goat')">Add an item</button>

        <ul>

            <li v-for="item in list">{ {item}}</li>

         </ul>

       </div>

    <script src="./vue.js"></script>

    <script>

        new View({

            the:'#app',

            data:{

                list:['Xiao Huang is very useless','Xiao Zhong has a lot of things','Xiao Lu's love brain']

            },

            watch:{

                // complex data type, these two parameters are meaningless, because the address has not changed

                // Therefore, in complex types, these two parameters are generally not written, because the values ​​​​of these two parameters are the same, even if they are written, only one is written.

                list(newValue,oldVaule){

                    console.log('data changed', newValue, oldVaule,);

                }

            }

        })

    </script>

   

</body>

AJAX

Ajax is a set of APIs that allow the browser to interact with the server.

Its role is to allow the browser to interact with the server.

It is a technique to partially refresh the page by requesting data from the server.

AJAX sends post request

<!-- AJAX sends post request

1. Instantiate a request object

2. Call the open method, pass the request method and request address

3. Set the request header

4. Set the callback function after the request is successful

5. Send request

Parameters passed in the get request: spliced ​​directly after the url address, which is not very secure.

 Post request passing parameters: passing in the send() method -->

<script>

// 1. Instantiate a request object

let xh = new XMLHttpRequest

// 2. Call the open method, pass the request method and request address

xh.open('post','https://autumnfish.cn/api/user/register')

// 3. Set the request header (fixed syntax, just paste)

xh.setRequestHeader("Content-type","application/x-www-form")

// 4. Set the callback function after the request is successful

xh.onload = function(){

// console.log(xhr.response);

let obj = JSON.parse(xhr.response)

 console.log(obj);

}

// 5. Send request

// Request format: "key=value'

 xh.send('username=Peng Lei')

 </script>

</body>

</html>

Get request submission parameters

<body>

    <!-- Instantiate a request object

    Call the open method, set the request method and request address

    After the setting request is completed, go to the callback function

    Call the send method to complete the request -->

    <script>

    // instantiate a request object

    let xh = new XMLHttpRequest

    // Call the open method, set the request method and request address

    xh.open('get','https://github.com/AutumnFish/testApi')

    // Call the onload method, set the callback function after the request is completed

xh.οnlοad=function(){

    // console.log(xh.response);

    let jokes = JSON.parse(xh.response)

    console.log(jokes);

}

    // Call the send method to complete the request

    xh.send()

    </script>

</body>

Guess you like

Origin blog.csdn.net/m0_73495603/article/details/129290698