1. Vue. Js overview

\quad vue.js is an incremental framework for building user interfaces that helps reduce unnecessary DOM manipulation (which can be expensive).

  • Progressive framework: Declarative rendering -> component systems -> client routing -> centralized state management -> Project artifacts.
  • Dom manipulation: An HTML document is a DOM tree after being parsed by the browser. To change the structure of HTML, you need to use JS to manipulate the DOM.

2. Vue. Use js

2.1 Basic steps of using Vue

  • 1. Provide labels for filling data
  • 2. Import the vue.js library file – click here to download it

2.2 instance

The < body > < div id = "app" > < div > {{MSG + '-'}} < / div > < / div > / / download from the website of vue. Js file, Put it in the js directory under the project directory <script type="text/javascript" SRC ="js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({// el- mount position of element (value can be CSS selector or DOM element) el: '#app', // model data (value is an object) data: {MSG: 'Hello World'}}); </script> </body>Copy the code

2.3 Vue code operation principle analysis

\ quad for the < div > {{MSG + ‘-‘}} < / div > this code, the browser does not know how to parse. It appears properly on the browser page because the Vue framework parses the Vue code into native JS code.

3.Vue template syntax

3.1 instruction

The format of the instructions in \quad Vue begins with v-.

The 3.2 V-cloak command solves flashing problems

\ Quad mentioned earlier that the Vue framework parses the code into native JS code, which is then rendered by the browser, so users may be able to see the following code when refreshing the page. Use v-cloak to avoid this display. Cloak = v-cloak = cloak = cloak = cloak = cloak

 <style type="text/css">
    [v-cloak]{
      display: none;
    }
 </style>
Copy the code

Then add the V-cloak directive to the div:

 <div id="app" v-cloak>
      {{msg+'------'}}
 </div>
Copy the code

The essence of quad’s ability to achieve this effect is to hide the content by style, then replace the values in memory, and then display the final result.

3.3 V-text of data binding instructions

The \quad v-text command is used to insert plain text, e.g. displays the same effect as the previous {{MSG +’——‘}} command.

3.4 Data binding instruction V-HTML

The \quad V-HTML directive is used to insert HTML fragments, such as adding to data

Msg1 :'<br>123<br><h2> Test contents </h2>'Copy the code

use

<span v-html="msg1"></span>
Copy the code

Insert HTML snippets.

3.5 Data binding instruction V-pre

The quad V-pre command is used to display raw information, skipping the parsing phase of Vue. Such as:

<span v-pre>{{this sentence will not be compiled}}</span>Copy the code

Display effect:

3.6. Data corresponding instruction V-once

\quad responsiveness refers to changes in the content of the page caused by changes in the data. If you open a browser, use F12 to go to the console and use vm. MSG =123 to modify the content. But use:

<div id="app" v-once> <p>{{msg+'------'}}</p> <span v-text="msg"></span> <span v-html="msg1"></span> <span }}</span> </div>Copy the code

The V-once directive states that the code block is compiled only once, and that without responsiveness, the page content cannot be modified through the console.

3.7 Two-way binding V-model of data

The bidirectional binding of quad data means that the contents of Model and View are updated synchronously. Such as:

<input type="text" v-model='msg'>
Copy the code

This effect can be achieved:

Note: If you change the value of MSG in the View, the MSG in the Model will also be changed. If you change the value in the Model through Console, the View will also be displayed.

3.8 V-ON Binding of Events

\ quad example:

       <p>{{num}}</p>
       <button v-on:click="num++">+1</button>
       <button v-on:click="num--">-1</button>
Copy the code

The initial value of num in data is zero:

But num++,num– functions like this are usually written in a separate function to improve readability:

 <button v-on:click="add">+1</button>
 <button @click="minus">-1</button>
Copy the code

You can use @ instead of v-on:.

methods:{
          add:function () {
            this.num++
          },
          minus:function(){
            this.num--
          }
        }
Copy the code

3.9 Passing event Parameters

\quad In the previous example, we extracted operations such as num++,num– into the function, so for cases where arguments need to be passed in the function:

<button v-on:click="add(num,$event)">+1</button>
<button @click="minus">-1</button>
Copy the code
methods:{ add:function (num,event) { if(num<10){ ++this.num } console.log(event.target.innerHTML) Function (event){console.log(event.target.tagname) this.num--}}Copy the code

Effect:

The tagName is BUTTON, innerHTML is +1;

Conclusion:

  • 1. If the event is directly bound to the function name, the event object is passed as the first argument to the event function by default.
  • 2. If the event binding function is called, the event object must be displayed as the last argument and the name of the event object must be $event.

3.10 V.top Prevents bubbling

Suppose we change the code to this:

<div id="app" v-on:click="add(num,$event)">
       <p>{{num}}</p>
       <button>+1</button>
       <button @click="minus">-1</button>
</div>
Copy the code

\ Quad can see that clicking +1 does +1, but clicking -1 does not change the number. This is because the action in button is the same as the action in div, one minus one plus, so it doesn’t look like the numbers are changing.

\ Quad therefore needs to prevent bubbling in minus:

 minus:function(event){
            event.stopPropagation();
            console.log(event.target.tagName)
            this.num--
          }
Copy the code

This approach can also be simplified as:

<button v-on:click.stop="minus">-1</button>
Copy the code

3.11v.prevent Blocks the default operation

\ Quad has the following A tag:

< a href = "http://www.zhihu.com" target = "_blank" v - on: click = "another $event ()" > zhihu < / a >Copy the code

As we know, clicking “Zhihu” will jump to the home page of Zhihu by default, and bind another function. But add in another:

event.preventDefault();
Copy the code

This default behavior can be prevented. At the same time, this method can also be simplified as:

v-on:click.prevent
Copy the code

3.12v.elf only itself can trigger events

\quad means to exclude the situation triggered by bubbling, in which case:

<div id="app" v-on:click.self="add(num,$event)">
       <button v-on:click="add(num,$event)">+1</button>
       <button v-on:click="minus">-1</button>
</div>
Copy the code

The add() method is called only when “+1” is clicked, and the Add () method that bubbles up as a result of clicking “-1” is not executed.

3.13 Concatenation between modifiers

Of course, qualifiers can be concatenated, for example: v.on:click:prevent. Self will prevent itself and the bubble calling method.

3.14 v.email /v.delet key modifier

\quad For the user to submit the form, we need to realize that the user can also click Enter to submit, at this time need to use v-on:keyup command. Such as:

<body> <div id="app"> <form action=""> <div> username: <input V-model ="username" type="text"  <input v-model="password" v-on:keyup.enter="handel" type="text" /> </div> <div> <input type="button" V-on :click=" Handel "value=" submit" /> </div> </form> </div> <script type="text/javascript" SRC ="js/vue.js"></script> <script  type="text/javascript"> var vm = new Vue({ el: '#app', data: { username: '', password: '' }, methods: { handel: function(username) { console.log(this.username, this.password); }}}); </script> </body>Copy the code

\quad can be implemented, keyboard enter can also submit the form. Note: V-on :keyup must be followed by. Enter, otherwise any key can be pressed to trigger the submission operation. V.d elete similarly.

3.15 Customizing Key Modifier

First of all, we know that each key on the keyboard has a unique numeric identifier, called keyCode. You can use:

<div>
     <input type="text" v-on:keyup="number" />
</div>
Copy the code
number: function(event) {
            console.log(event.keyCode);
          }
Copy the code

View the corresponding value. \ Quad, knowing the value of each key on the keyboard, can use: V-on :keyup.65 to define the operation of the A key and v-on:keyup.32 to define the operation of the space bar.

\quad According to the official website, you can configure an alias to alias the corresponding ASCII keypad number. For example, vue.config.keycodes. show = 65;

3.16 V-bind Attribute binding

We know that we can bind the tag name to the link in the tag, but we need to use a variable instead of the URL:

<a href=" _blank" target="_blank">Copy the code
data: {
          url: 'http://www.zhihu.com'
        },
Copy the code

If you click zhihu, an error will be reported. You need to use the V-bind command:

<a v-bind:href=" _blank" target="_blank">Copy the code

Or it can be shortened to:

<a :href=" _blank" target="_blank">Copy the code

In fact, v-bind is also used in the two-way data binding v-model. Such as:

<input type="text" v-bind:value="url" v-on:input="write" />
Copy the code
write: function(event) {
            this.url = event.target.value;
          }
Copy the code

You can also achieve the same effect as the V-Model. Alternatively, it can be simply shortened to:

v-on:input="url=$event.target.value"
Copy the code

3.17 V-bind class style processing

\ Quad can use v-bind:class to dynamically switch classes:

<style> .boder { border: 4px solid red; width: 80px; height: 100px; } .background { background: blue; } .font { color: white; } .circle { width: 100px; height: 100px; border-radius: 50px; } </style> <body> <div id="app"> <div v-bind:class="{active:isActive,backgroundColor:isBack}"></div> <button V-on :click="change"> </button> <button V-on :click="change1"> </button> </div> <script type="text/javascript"  src="js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#app', data: { isActive: 'true', isBack: 'true' }, methods: { change: function() { this.isActive = ! this.isActive; }, change1: function() { this.isBack = ! this.isBack; }}}); </script> </body> </html>Copy the code

Array binding for v-class:

The < body > < div id = "app" > < div v - bind: class = "[boderClass backgroundClass]" > < / div > < button v - on: click = > "change" hidden < / button > <button V-on :click="return1"> display </button> </div> <script type="text/javascript" SRC ="js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#app', data: { boderClass: 'boder', backgroundClass: 'background' }, methods: { change: function() { (this.boderClass = ''), (this.backgroundClass = ''); }, return1: function() { (this.boderClass = 'boder'), (this.backgroundClass = 'background'); }}}); </script> </body>Copy the code

Display effect:

Other notes:

  • 1. Object binding and array binding can be used together, for example:
 <div v-bind:class="[boderClass,backgroundClass,{font:isWhite}]">
Copy the code
  • 2. The value of the class binding can be simplified, for example:
arrayClass: ['circle', 'background', 'boder']
Copy the code

Multiple properties can be bound to a property name.

  • 3. The default class is retained. Such as:
<div class="font" V-bind :class="arrayClass">Copy the code

Instead of being overwritten, the FONT property is displayed along with the properties in arrayClass.

3.18 Style processing (inline style processing)

You can also use v-bind:style= “” to change the style. For example:

<div v-bind:style="{border:borderStyle,background:backgroundStyle,width:widthStyle,height:heightStyle}"></div>
Copy the code
data: {
          borderStyle: '2px solid red',
          backgroundStyle: 'blue',
          widthStyle: '80px',
          heightStyle: '100px',
          circlestyle: 'circle'
        },
Copy the code

The above way of writing can be abbreviated as:

<div v-bind:style="circlestyle"></div>
Copy the code
circlestyle: {
            width: '100px',
            height: '100px',
            border: '2px solid blue',
            background: 'red'
          }
Copy the code

You can also use arrays in v-bind:style. For example:

 <div v-bind:style="[circlestyle,circlestyle1]"></div>
Copy the code

Note: If the attributes in circleStyle and circleStyle1 are duplicated, the latter overrides the former, and the non-duplicated attributes complement each other.

4. Branch cycle structure

Branch structures include:

  • v-if
  • v-else
  • v-else-if
  • V-show (controls whether elements are displayed)

4.1 branch

First, we know that methods can use if/else to implement the corresponding logic:

Method: {calculate: function() {if (this.score > 90) {this.result = 'calculate '; } else {this.result = 'good '; }}}Copy the code

You can also use this method:

< div v - if = 100 > = "score && score > = 90" > good < / div > < div v - else - if = "score < 90 && score > = 80" > good < / div >Copy the code

4.2 cycle

For the for loop, use the V-for directive, as an example:

data: {
          weeks: ['monday','tuesday','wednesday','thrusday','friday','saturday','sunday']
        },
Copy the code

Through:

<ul>
        <li v-for="week in weeks">{{week}}</li>
</ul>
Copy the code

Note:

  • Here week is an alias used to represent an example in an array.
  • In is the keyword

If you need an index, you can use it like this:

"Li: key = 'index' v - for =" (week, the index) in weekes "> {{week}} {{index + 1}} - week < / li >Copy the code

Index is also a keyword.

The 4.3 V-for loop traverses the object

For example, there is an object in data:

 aMan: {
            username: 'zhangsan',
            password: 'password',
            timestamp: '2020-02-20'
          }
Copy the code

To loop through the properties of an object one by one:

 <div v-for="(v,k,i) in aMan">{{v+'---'+k+'---'+i}}</div>
Copy the code

V represents value, K represents key, and I represents index.

5. Common Vue features

Overview: 1. Form operations 2. Custom instructions 3. Listener 6. Life cycle

5.1 VUe-based form operations

  • Input Single line of text
  • Textarea multi-line text
  • Select drop down multiple selections
  • Radio radio buttons
  • The checkbox boxes,

Example:

  • 1. Input Single-line text
<input type="text" v-model="uname" />
Copy the code
  • 2. Select a drop-down list
<div> <span> <select V-model ="langunage" multiple="true"> <option value="1">Java</option> <option value="2">c</option> <option value="3">c++</option> <option value="4">python</option> </select> </div>Copy the code
  • 3. The radio radio
<div> <span> -- Label name set to consistent, <input type="radio" name="sex" id="male" value="1" V-model ="gender" /> <label for="male"> male </label> <input Type ="radio" name="sex" id="female" value="2" V-model ="gender" /> <label for="female"> </label> </div>Copy the code
  • 4. The checkbox boxes
<div> <span> </span> <input type="checkbox" ID ="ball" value="1" V-model ="hobby" /> <label for="ball"> basketball </label> <input Type ="checkbox" id="sing" value="2" V-model ="hobby" /> <label for="sing"> </label> <input type="checkbox" ID ="jump" Value ="3" V-model ="hobby" /> <label for="jump"> </label> <input type="checkbox" ID ="rap" value="4" V-model ="hobby" /> <label for="rap">rap</label> </div>Copy the code
  • 5. Textarea multi-line text
</span> <textarea V-model ="resume" cols="30" rows="2"></textarea> </div>Copy the code

5.2 Form field modifiers

  • Number: Converts to a value

Example:

<input type="text" v-model.number="len" size="2" disabled="disabled" />
Copy the code
  • Trim: Remove starting and ending Spaces
<input type="text" v-model.trim="message" size="10" />
Copy the code
  • Lazy: Toggles the input event to the change event
 <div v-text="message"></div>
        <input type="text" v-model.lazy="message" />
Copy the code

\quad Changing the contents of the input does not immediately change the contents of the div display, it only causes change when the input box loses focus.

5.3 Custom Commands

Examples given on \ Quad’s website:

{vue. directive('focus', {inserted: Function (el) {// el specifies the element el.focus(); }});Copy the code

The effect is: plusv-focusAfter identification, the focus automatically corresponds to the selected area each time the page is opened.

5.4 User-defined Commands with Parameters

According to the description on the official website, examples:

Vue.directive('color', { bind: Function (el, binding) {// specify the backgroundColor of the element as color el.style.backgroundColor = binding.value. }});Copy the code

Specify parameters in input:

<input type="text" v-color="msg" />
Copy the code

MSG content:

msg: {
            color: 'red'
          },
Copy the code

5.5 Local Instructions

\ Quad may register local directives by adding directives in new Vue() :

directives: { color: { bind: Function (el, binding) {// specify the backgroundColor of the element as color el.style.backgroundColor = binding.value. }}}Copy the code

Unlike global directives, local directives can only be used within this component.

5.6 Calculating Attributes

\ Quad uses computed attributes to make template content more concise.

computed: { reverseMessage: function() { return this.message .split('') .reverse() .join(''); }}Copy the code

Properties can be obtained by calling the property name directly:

<span v-text="reverseMessage"></span>
Copy the code

The difference between computed properties and methods:

  • 1. Calculated attributes are cached based on their dependencies.
  • 2. The function is executed every time it is called. There is no cache.

5.7 the listener

  • 1. Listeners are used to perform asynchronous or expensive operations when data changes.

For example, enter the first and last name to automatically concatenate the name:

watch: { firstname: function(val) { this.fullname = val + ' ' + this.lastname; }, lastname: function(val) { this.fullname = this.firstname + ' ' + val; }}Copy the code

Call the name of the listener to get the properties of the listener:

<input type="text" v-model="fullname" size="5" />
Copy the code

Effect:

Example: Verify that the user name exists

The < div > < span > name: < / span > < input type = "text" v - model. Lazy = "uname" / > < span > {{message}} < / span > < / div >Copy the code
methods: { checkname: Function (uname) {function(uname) {function(uname) {function(uname) {function(uname) {function(uname) {function(uname) { SetTimeout (function() {if (uname == 'admin') {that.message = 'User name already used, please select another user name... '; } else {that.message = 'User name can be used... '; }}, 3000); } }, watch: { uname: function(val) { this.checkname(val); This. message = 'Username checking... '; }}Copy the code

5.8 Vue Filters

Custom filters:

Vue. Filter (' filter name ',function(value){//Copy the code

Define a filter according to the instructions on the website:

Vue.filter('upper1', function (val) {
      return val.charAt(0).toUpperCase() + val.slice(1);
    });
Copy the code

Calling filters:

    <div>
      {{msg|upper1}}
    </div>
Copy the code

Filters can be connected in series:

    Vue.filter('lower', function (val) {
      return val.charAt(0).toLowerCase() + val.slice(1);
    });
Copy the code

Val defaults to the data to be processed, namely lower, calling the method:

    <div>
      {{msg|upper |lower}}
    </div>
Copy the code

Another way to call:

    Vue.filter('formate', function (val) {
      return val.slice(1);
    });
Copy the code
The < div > < a v - bind: href = "url | formate" target = "_blank" > test jump < / a > < / div >Copy the code

Filter function with parameters:

      Vue.filter('add', function(val, formateType) {
        if (formateType == 'yyyy-mm-dd') {
          var formateDate = '';
          formateDate +=
            val.getFullYear() +
            '-' +
            (val.getMonth() + 1) +
            '-' +
            val.getDate();
        }
        return formateDate;
      });
Copy the code
        data: {
          formateType: 'yyyy-mm-dd',
          date: new Date()
        },
Copy the code

Display effect:

5.9 Life Cycle

Main stages:

  • 1. Mount (initialize related attributes)
  • 2. Update (operation to change an element or component)
  • 3. Destroy (destroy related attributes)

In Vue, methods are expressed as the following stages:

  • BeforeCreate: called after instance initialization and before data observation and event configuration.
  • Created: called immediately after an instance is created.
  • BeforeMount: Called before mounting begins.
  • Mounted: This hook is invoked after the vm.$el is mounted to the instance.
  • BeforeUpdate: Called when data is updated and occurs before the virtual DOM is patched.
  • Updated: This hook is called after the virtual DOM is re-rendered and patched due to data changes.
  • BeforeDestroy: Called before instance destruction.
  • Destroy: called after the instance is destroyed.

For example:

<div id="app"> <div> <input type="text" v-model=" MSG "/> <div> <button V-on :click="update" V-on :click="destroy"> </button> </div>Copy the code
methods: { update: function() { this.msg = '456'; }, destroy: function() { this.$destroy(); }},Copy the code
        beforeCreate: function() {
          console.log('beforeCreate');
        },
        created: function() {
          console.log('created');
        },
        beforeMount: function() {
          console.log('beforMount');
        },
        mounted: function() {
          console.log('mounted');
        },
        beforeUpdate: function() {
          console.log('beforeUpdate');
        },
        updated: function() {
          console.log('updated');
        },
        beforeDestroy: function() {
          console.log('beforeDestroy');
        },
        destroyed: function() {
          console.log('destroyed');
        }
Copy the code

Define two buttons to represent update and delete operations, and you can see the functions called at each stage:

6.MVVM development ideas

\ Quad MVVM is the abbreviation of Model-view-viewModel, Model to achieve Model control, View control page display, VM control logic.

  • DOM Listeners – DOM to monitor
  • Data Bindings- Data Bindings

7. Script type

\quad type Specifies the MIME type of the script as an attribute. The MIME type consists of two parts: media type and subtype. For JavaScript, the MIME type is “text/ JavaScript “. The default type in HTML5 is “text/javascript”.

Some common values:

  • Text /javascript (default)
  • text/ecmascript
  • application/ecmascript
  • application/javascript
  • text/vbscript

8. Project Practice – Library management system

Array API:

1. Variation method:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

2. Replace arrays (generate new arrays)

  • filter()
  • concat()
  • slice

3. Change array data in response:

Vue. Set (vm.bookName, 2, 'brother '); $set(vm.page1, 1); $set(vm.page1, 1); $set(vm.user, 'age', 18);Copy the code

4. Application scenarios of common features

  • Filter (formatting date)
  • Custom directives (get form focus)
  • Calculate properties (count books)
  • Listener (verify book existence)
  • Declaration cycle (Book data processing)

5. The code

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, "/> <meta http-equiv=" x-UA-compatible" content="ie=edge" /> <title>Document</title> <style type="text/css"> [v-cloak] { display: none; }. GridTable {/* Set the margin attribute */ margin: auto; width: 500px; text-align: center; } .gridTable table { width: 100%; */ * border-collapse: collapse; /* border-collapse: collapse; /* border-collapse: collapse; } .gridTable th, td { padding: 10; /* dashed line */ border: 1px solid RGB (15, 15, 15); /* dashed line */ border: 1px solid RGB (15, 15, 15); height: 35px; line-height: 35px; } .gridTable th { /* background-color: rgb(93, 205, 240); */ } .gridTable total { /* height: 300px; line-height: 300px; background-color: orange; border-top: 1px orange solid; */ } .center { text-align: center; } </style> </head> <body> <div id="app" v-cloak> <div class="gridTable"> <table> <tr> <th> <div class="center"> <p V - HTML = "message" > < / p > < / div > < / th > < / tr > < / table > < table > < tbody > < tr > < th > < label for = "id" > no. : </label> <input type="text" id="id" size="3" v-model="newBookId" v-bind:disabled="noEditBookId" v-focus /> </th> <th> <label for="name"> </label> <input type="text" id="name" size="12" V-model ="newBookName" /> </th> <th> <label for="name"> </label> <input type="text" id="userName" size="8" v-model="newUserName" /> </th> <th> <button v-on:click="addItem" V-bind :disabled="submitFlag"> submit </button> </th> </tr> </tbody> </table> <table> <tr> <th> <div class="total"> <span> Number of books: < / span > < span > {{total}} < / span > < / div > < / th > < / tr > < / table > < table > < thead > < tr > < th > id < / th > < th > name < / th > < th > < / th > borrowed time The < th > borrower < / th > < th > action < / th > < / tr > < thead > < tbody > < div > < tr: key = "index" v - for = "(book, index) in books" > <td>{{book.id}}</td> <td>{{book.name}}</td> <td>{{book.lendTime |formate}}</td> <td>{{book.userName}}</td> <td> <a Href = "" v - on: click. Prevent =" editBook (book. Id) "> edit < / a > < span > | < / span > < a href =" " V - on: click. Prevent = "called deleteItem (book. Id)" > delete < / a > < / td > < / tr > < / div > < / tbody > < / table > < / div > < p class = "center" > < span style="color: red; font-weight: bold;" >{{tips}}</span> </p> </div> <script type="text/javascript" src=".. /js/vue.js"></script> <script type="text/javascript"> Vue.filter('formate', function(val) { return ( val.getFullYear() + '-' + val.getMonth() + '-' + val.getDate() + ' ' + val.getHours() + ':' + val.getMinutes() + ':' + val.getSeconds() ); }); Vue.directive('focus', { inserted: function(parm) { parm.focus(); }}); var vm = new Vue({ el: '#app', data: { noEditBookId: false, submitFlag: false, newBookName: '', newBookId: ' 'newUserName: "' the message: '< h2 > - welcome to use the books management system management system V1.0 - < h2 >', tips: "', books: []}, the methods: {addItem: function() { if (this.noEditBookId == false) { if (this.newBookName ! = '') { var el = {}; el.name = this.newBookName; el.id = this.newBookId; el.lendTime = new Date(); el.userName = this.newUserName; this.books.push(el); } else {this.tips = 'Title cannot be empty! '; } this.noEditBookId = false; } else {/ / according to the current ID to update the array of data / / use the array traversal, positioning to need to modify the array object / / this. Books. Some (function (val) {/ / this is the function in Vue, So this here refers to Windows) //}); This.books. some(parm => {// In this case this also refers to Windows if (parm. Id == this.newBooKid) {parm. Name = this.newbookName; parm.userName = this.newUserName; return true; }}); this.noEditBookId = false; } // After modifying or adding books, empty the input box (this.newBookId = "), (this.newBookName = "), (this.newUserName = "); }, deleteItem: // var index = this.books.findIndex(function(parm) {// return parm.id == id; / /}); // this.books.splice(index, 1); This.books = this.books.filter(function(parm) {return parm. = id; }); }, editBook: Var readToEdit = this.books.filter(function(item) {return item.id ==  id; }); this.newBookId = readToEdit[0].id; this.newBookName = readToEdit[0].name; this.newUserName = readToEdit[0].userName; this.noEditBookId = true; } }, computed: { total: function() { return this.books.length; } }, watch: { newBookName: function(parm) { var flag = this.books.some(function(item) { return item.name == parm; }); if (flag) { this.submitFlag = true; } else { this.submitFlag = false; }}, mounted: function() {var data = [{id: 1, name:}}, mounted: function() {var data = [{id: 1, name:}}, mounted: function() {var data = [{id: 1, name:] LendTime: new Date(), userName: 'j3'}, {id: 2, name: j4, lendTime: new Date(), userName: 'j4'}, {id: 1 3, lendTime: new Date(), userName: 'wang5'}]; this.books = data; }}); </script> </body> </html>Copy the code

Page:

9. Reference documents

  • 1. Liao Xuefeng official documentation – MVVM www.liaoxuefeng.com/wiki/102291…