Vue case: todolist

Time:2021-6-10

Vue case: todolist

ToDoList

requirement

  • Objective:
    • Display an input box, a button
    • Input the content in the input box, click the button to display the content in the page, and then the input box will return to blank
      Vue case: todolist
  • To fully understand this little demo, you need some prerequisites:
    • vueBasic instruction
    • Preliminary understandingJavaScriptScope in andthiskeyword
    • Usage of Vue global components and local components

The most common way

<div id="app">
    <input type="text" v-model="inputValue"/>  <!--  V-model realizes bidirectional data binding -- >
    Add < / button > <! [email protected] Click triggers a click event -- >
    <ul>
        <li v-for="item in list">{{ item }}</li>  <!--  V-for binding data to loop rendering -- >
    </ul>
</div>
<script src=" https://cdn.jsdelivr.net/npm/vue "></script>  <!--  Introducing Vue -- >
<script type="text/javascript">
    Var app = new Vue ({// create a new instance object)
        El: short for '# app' // El: element, which is used to specify the elements (including all child elements) taken over by Vue application
        data: {  // data:data This is the data in the Vue instance
            List: [], // data corresponding to V-for instruction
            Inputvalue '' // data binding corresponding to V-model
        },
        Methods: {// method
            Button click: function () {// method corresponding to @ Click
                //Add the content in the input box to the list. This points to the app instance
                this.list.push(this.inputValue);
                //Clear the input box after adding
                this.inputValue = '';
            }
        }
    })
</script>

Global component implementation

<div id="app">
    <input type="text" v-model="inputValue"/>  <!--  V-model realizes bidirectional data binding -- >
    Add < / button > <! [email protected] Click triggers a click event -- >
    <ul>
        <!--  Using components -- > <-- Pay attention to the naming rules. Todoitem of the global component should be written as todo item -- >
        <todo-item v-bind:content='item' v-for='item in list'></todo-item>
    </ul>
</div>
<script src=" https://cdn.jsdelivr.net/npm/vue "></script>  <!--  Introducing Vue -- >
<script type="text/javascript">
    //The component method in Vue is used to define a global component
    Vue. Component ('todoitem ', {// the component name is todoitem
        Props: ['content '], // the value passed from the parent component, that is, the content value to be rendered
        Template: '< li > {{content}} < / Li >' // HTML template, in which the interpolation expression is still used to display the content value
    })
    Var app = new Vue ({// create a new instance object)
        El: short for '# app' // El: element, which is used to specify the elements (including all child elements) taken over by Vue application
        data: {  // data:data This is the data in the Vue instance
            List: [], // data corresponding to V-for instruction
            Inputvalue '' // data binding corresponding to V-model
        },
        Methods: {// method
            Button click: function () {// method corresponding to @ Click
                //Add the content in the input box to the list. This points to the app instance
                this.list.push(this.inputValue);
                //Clear the input box after adding
                this.inputValue = '';
            }
        }
    })
</script>
  • In fact, compared with the most common way we used before, here is nothing more than putting the previous<li v-for="item in list">{{ item }}</li>
    It was replaced by<todo-item v-bind:content='item' v-for='item in list'></todo-item>
    Then a global component is definedTodoItem
  • So, what do components correspond to normal modes?
    • We useVue.componentMethod defines aTodoItemThe global component of thetemplateProperty is used to replace<li>{{ item }}</li>Of
    • After registering the component, we can use itdivDirect use in<todo-item></todo-item>that will do
    • In addition, in order to replace thev-for='item in list'
      We use thev-bind:content='item'as well asv-for='item in list'
    • The last step: component value, we now only havev-bind:connentandcontentWe haven’t transferred the value yet, so we usepropsProperty to accept the value passed by the parent componentinputIn addition, the outermost layer of the Vue instance here is actually the parent component.)
  • Let’s sort out the whole process
    • stayinputBox and clickadd to, triggerbuttonClick()data.listadd toinputBox
    • v-foruseitemTraverseddata.listAnd pass the value through thev-bind:contentPass on to<todo-item></todo-item>label
    • Finally, the interpolation expression is usedcontentPrint out

Local component implementation

<div id="app">
    <input type="text" v-model="inputValue"/>  <!--  V-model realizes bidirectional data binding -- >
    Add < / button > <! [email protected] Click triggers a click event -- >
    <ul>
        <!--  Note the naming. The name here is based on the property name of components in the Vue instance -- >
        <todo v- bind:content= 'item' v-for='item in list'></todo>  <!--  Using components -- >
    </ul>
</div>
<script src=" https://cdn.jsdelivr.net/npm/vue "></script>  <!--  Introducing Vue -- >
<script type="text/javascript">
    Var todoitem = {// defines the name of the local component as todoitem
        Props: ['content '], // accept the value passed by the parent component
        Template: '< li > {{content}} < / Li >', // HTML template
    }
    Var app = new Vue ({// create a new instance object)
        El: short for '# app' // El: element, which is used to specify the elements (including all child elements) taken over by Vue application
        Components: {// register components
            //It is defined as todoitem, and now it is named todo in the instance. When it is used, the latter shall prevail
            todo: TodoItem,
        },
        data: {  // data:data This is the data in the Vue instance
            List: [], // data corresponding to V-for instruction
            Inputvalue '' // data binding corresponding to V-model
        },
        Methods: {// method
            Button click: function () {// method corresponding to @ Click
                //Add the content in the input box to the list. This points to the app instance
                this.list.push(this.inputValue);
                //Clear the input box after adding
                this.inputValue = '';
            }
        }
    })
</script>
  • In fact, the local components here are easy to master. Before comparison, the global components are usedVue.componentMethod, and the local component directly writes the entire content as aobject
  • Then, in the Vue instance, through thecomponentsProperty, register the component as a property value, and finally use the component directly

Add a function

requirement

  • BeforeToDoListOn this basis, we need to add a function:
    • Click an item and it will disappear
    • Enter in the input box to add an item
      Vue case: todolist
  • Knowledge premise:
    • Component value transfer
    • JavaScript string method
    • Vue key modifier

Component implementation

<div id="app">
    <!--  The event modifier points the carriage return event Keyup. Enter to the buttonclick function -- >
    <input type="text" v-model="inputValue" @keyup.enter="buttonClick"/>
    < button type = "button" @ Click = "button click" > Add < / button >
    <ul>
        <todo-item v-bind:content = 'item' 
                   v-for = '(item, index) in list'
                   v-bind:index = 'index'
                   v-on:delete = 'parentDelete'>
        </todo-item>
    </ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script type="text/javascript">
    Vue.component('TodoItem', {
        Props: ['content ','index'], // accept the value from the parent component
        //Click the element to trigger the child delete event of the subcomponent
        template: '<li @click="childDelete">{{ content }}</li>',
        methods: {
            /*The child component triggers an event named delete, which will be monitored by the parent component to trigger parentdelete
            The value passed by the child component to the parent component includes not only the event name delete, but also an index to represent the subscript of the element*/
            childDelete: function(){
                this.$emit('delete', this.index);  // This.index comes from the value accepted by props
            }
        }
    })
    var app = new Vue({
        el: '#app',
        data: {
            list: [],
            inputValue: ''
        },
        methods: {
            buttonClick: function(){
                this.list.push(this.inputValue);
                this.inputValue = '';
            },
            //When the parent component detects that the delete event of the child component is triggered
            Parentdelete: function (index) {// accepts the value passed by the subcomponent. The index comes from this.index of the subcomponent
                this.list.splice(index, 1); // JS string method to delete the element with the specified subscript
            }
        }
    })
</script>
  • Obviously, we shouldn’t read the code from top to bottom. We should think about the function
  • The function we want to achieve is: click an element to make it disappear, but whether an element disappears in a child component is determined by the parent componentlistAndv-forJointly determine the value of the rendering
  • Therefore, our general thinking should be as follows:
    • Click an element, and let the child component pass the subscripts of the element to the parent component
    • The parent component is then deleted in thelistThe whole process can be realized by using the subscript element in
  • Therefore, our key operations are:
    • When defining local components, givetemplateProperty of the HTML template to addchildDelete, trigger when clicking
    • adoptthis.$emittakethis.indexTo the parent component, but we need to bind an event for the parent component to listen in real time. We name itdelete
    • Parent component passedv-on:deleteWhen the monitor arrives, it will triggerparentDeleteTo delete the element
    • howeverparentDeleteWe definitely need to know the element subscript, so we need to pass the subscript to the subcomponent at the beginning, and then the subcomponent returns it to theparentDelete
  • The personal feeling of transferring values between child components and parent components depends on when they are used. For example, the multiple values corresponding to multiple events here. That is to say, when we transfer values, we must find out what the event corresponding to this value is

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]