preface

This is the 7th day of my participation in the August More Text Challenge. Coincides with the nuggets in August more challenge, must have many beginners Vue friend often see a word of English component, don’t know how to write components as well as the understanding of the concept of slot slot time make a headache, after followed the knock on the code, the in the mind may be thought of component and slot could actually so, greatly reduces the coupling of the code, Easy to achieve the reuse of the code, too tight ah eyebrow! Talk less, today I hope to help you through this small case. Come on, mutual encouragement!

Page effect display

Demand analysis

First of all, enter the user management list, to obtain all the information data of user registration, and dynamic rendering through the data table, each user exclusive line, and according to the user ID number given a fixed serial number.

Secondly, the last column of the table as the operation column, by pressing the delete button, according to the user ID background to delete the user information and other binding data, after the deletion, dom structure changes, automatic rendering table, serial number –, the specified row disappears, to complete the deletion operation.

Finally, in order to provide better user experience, timely feedback will be given to the delete operation result after clicking the delete button. In case of misoperation, users can click the cancel button to cancel the deletion operation. In addition, after the deletion operation is complete, the user is asked once to return to the main menu page.

Code implementation

[v-cloak] {
    display: none;
}
Copy the code

Why use the V-cloak directive to set the style here?

Since the data table is loaded dynamically when the page is opened, when the network is slow or there is a lot of data loaded, the page is still loading Vue. Js, and Vue cannot render, then the page will display the Vue source code, such as the frequently used {{}}. The V-cloak command can be used to solve this problem.

In addition, these styles are removed from the bound HTML elements at the end of compiling the Vue instance.

For simple projects, using the V-Cloak directive is a good way to get around screen flickering. However, in large, engineered projects (webpack, Vue-Router) there is only one empty div element, and the contents of the element are implemented by routing mount rather than using the V-cloak directive.

<body>
    <div id="usersTable" v-cloak>
        <my-table id="my-table">
            <my-thead slot="my-thead"></my-thead>
            <my-tbody slot="my-tbody" v-for="(user, index) in users" v-bind:user="user" v-bind:index="index" v-bind:key="index" v-on:remove="delUser(index)"></my-tbody>
        </my-table>
    </div>
</body>
Copy the code

Warning: Component lists rendered with V -for should have explicit keys warning: Component lists rendered with V -for should have explicit keys

Q: So why provide one for componentskey ?

  1. To give Vue a hint so that it canTrace each nodeThe identity of the
  2. To reuse and reorder existing elements, you need to provide one for each itemThe only keyattribute
// Set slot in myTable
Vue.component('myTable', {
    template:
        '
      
      
      
       \ \ \ 
      
'
}); // Table header slot Vue.component('myThead', { props: ['user'].template: '< tr > \ < th > number < / th > \ < th > uid < / th > \ < th > user name < / th > \ < th > name < / th > \ < th > gender < / th > \ < th > < / th > birthday \ < th > age < / th > \ < th > < / th > \ mobile phone number password Delete \ ' }); // Table body slot Vue.component('myTbody', { props: ['index'.'user'].template: '\ {{index}}\ {{user.uid}}\ {{user.username}}\ {{user.name}}\ < / td > male \ < td v - else > women < / td > \ < td > {{user. Birthday}} < / td > \ < td > {{user. Age}} < / td > \ < td > {{user. Mobile}} < / td > \ < td > {{user. The password}} < / td > \ < td > < button id = "tableBut" v - on: click = "remove" > delete < / button > < / td > \ \ '.methods: { remove: function (object) { // Bind events inside the component this.$emit('remove', object); }}});Copy the code

Note: Use single or double quotation marks when defining component names.

Prop properties

Prop property: Similar to a custom attribute property and case insensitive like HTML.

  1. propsThe variable names in cannot be named with the dash split naming method, otherwise data binding cannot be performed.
  2. propsVariable names are either all lowercase or camelback.
  3. Accordingly, when naming a hump,v-bindThe binding property names are named with a dash (all lowercase is recommended); When it’s all lowercase, we’re done.

Component name name [Avoid pit]

Component name and registration component (registration component should use all lowercase letters) :

  1. When the component name is delimited with a dash, upper case is not allowed and all limits are lower case
    • Register components with the same name tag without changing case
  2. When component names are named with single-hump nomenclature, for example:myCom
    • camelCase(hump nomenclature)propThe name needs to use its equivalentkebab-case(delimited name) to register the component
      • Such as:my-com,my-ComDo not limit case, but try to use all lowercase tags
  3. When a component name appears double humped, for example:MyCom
    • And you can use the equivalentkebab-case(dash names) to register components (e.g., usemy-com)
      • Note:
        • You cannot register a component with the same or case-insensitive name in either case 2 or 3
        • An error is reported if an equivalent name is used:did you register the component correctly? For recursive components, make sure to provide the "name" option.
  4. When the component name has an N hump, for example:MyCoM,MyCoMpOnEnT.
    • All components are registered following the dash naming (for example:my-co-m.my-co-mp-on-en-t...)
  5. When component names do not follow dash and camel nomenclature (more than two consecutive uppercase or all lowercase letters), for example:MYcom,MyCOm,MYCOM,mycom...
    • The component can be successfully registered only in all lowercase cases

Vue core code

var vm = new Vue({
    el: '#usersTable'.data: {
        users: []},created: function () {
        $.ajax({
            type: 'POST'.url: '/user/getAllUsersInfo'.success: function (data) {
                initUsersInfo(data);
            },
            error: function (error) {
                alert(error)
            }
        });
    },
    methods: {
        delUser: function (index) {
            // The current serial number
            var num = index.valueOf();
            var uid = this.users[num].uid;
            var ans = confirm('Confirm to delete uid =>${uid}Users? `);
            if(ans === true) {
                this.users.splice(index, 1);
                $.ajax({
                    type: 'POST'.url: '/user/delUserByUid'.data: {
                        uid: uid
                    },
                    success: function (data) {
                        alert(data.msg);
                        var ifExit = confirm('Return to main menu page? ');
                        if(ifExit) {
                            window.location.href = '.. /index.html'; }},error: function (error) {
                        alert(error)
                    }
                });
            }else {
                alert('You cancelled the delete! '); }}}});function initUsersInfo(data) {
    if(jQuery.isEmptyObject(data)) {
        alert("User table empty ~")}else{ vm.users = data; }}Copy the code

First, the Vue data definition part defines an array to store user information, using the created method in vue.js, which is a lifecycle hook function. When a Vue instance is generated, this function will be called, and its specific function is to call the back-end interface. Get all user data under the TB_USER table, and then implement bidirectional data binding.

The first step is to delete the user id through the component’s internal this.$emit binding event (custom event name), but that alone is not enough. This does not help us to accomplish the desired function. The actual deletion method is defined in the methods of the Vue instance by passing the index, this.users[num]. Uid by passing the index subscript to get the user ID.

If you have any questions about component components or slot slots, visit vue.js.

At the end

Writing is not easy, welcome everyone to like, comment, your attention, like is my unremitting power, thank you to see here! Peace and Love.