Vue2.x study notes (a)


An inter-component communication

A method of communication between components, the five kinds of data transfer, the first 1 to 3 is more commonly used.

1. Sons props and components for communicating $ EMIT

1) Parent ==> pass value subassembly

  • Step1: first through the v-bindbinding properties to the parent custom assembly;
  • Step2: in subassembly propsdata receiving parent component transfer;
  • Step3: Use the data received in the subassembly.

2) sub ==> pass parent component values

  • Step1: Custom binding events in the parent component;
  • Step2: a trigger event in native subassemblies using the event function $emitevent triggers a parent custom components;
  • Step3: $emitThe parameter is passed back to the parent component data.
Vue.component("Child", {
    template: `
        <div>
            <input type="text" v-model="childData" @input='changeValue'/>
        </div>
    `,
    props: ['childData'], 
    methods: {
        changeValue(val){
            // 父组件自定义的事件一定是通过this.$emit()去触发
            // $emit(自定义的事件名, 消息)
            this.$emit('childHandler', val)
        }
    }
});

Vue.component("Parent", {
    data: {
        msg: "我是父组件"
    },
    template: `
        <div>
            <p>我是父组件</p>
            <Child :childData='msg' @childHandler='getDataHandler' />
        </div>,
    `,
    methods: {
        getDataHandler(val){
            console.log(val)
        }
    }
})

2. $ $ attrs the Listeners and inter-component communication multilayer

Data transmission between a first component has a problem manner: data transfer between the multi-layer assembly pass one layer. Vue2.4 began to provide $attrsand $listenersto solve this problem.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>组件通信二</title>
</head>
<body>
<div id="app"></div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    Vue.component("C", {
        data() {
            return {}
        },
        // 通过$attrs接收父组件传递来的数据
        template: `
            <div>
                <h4>这是子组件的内容</h4>
                <p>父组件传入子组件的数据:{{$attrs.messageParent}}</p>
                <button @click="cClickHandler">向父组件传递数据</button>
            </div>
        `,
        methods: {
            cClickHandler() {
                // 通过$listeners触发父组件监听的自定义事件向父组件传递数据
                this.$listeners.getSubData('组件C传入父组件数据')
            }
        }
    });

    Vue.component("B", {
        data() {
            return {}
        },
        template: `
            <div>
                <C v-bind="$attrs" v-on="$listeners"></C>
            </div>
        `,
        methods: {}
    });

    Vue.component("A", {
        data() {
            return {}
        },
        template: `
            <div>
                <B v-bind="$attrs" v-on="$listeners"></B>
            </div>
        `,
        methods: {}
    });

    let App = {
        data() {
            return {
                msg: "我是父组件的内容",
                msg2: "Hello sub component"
            }
        },
        template: `
            <div>
                <h4>这是一个父组件</h4>
                <p>注意:{{msg}}</p>
                <A :messageParent="msg2" v-on:getSubData="showData"></A>
            </div>
        `,
        methods: {
            showData(val)  {
                console.log(val);
                this.msg = val;
            }
        },
    };

    new Vue({
        el: "#app",
        data() {
            return {}
        },
        components: {
            App
        },
        template: "<App/>"
    })
</script>
</body>
</html>

3. Use central event bus for inter-component communication bus

The above are two ways to handle the components transfer data between father and son, parent-child relationship if the two components is not it? In this case the central event bus may be used by:
a new Vuetarget bus, and then by bus.$emitpassing data trigger events, by bus.$onreceiving the trigger event listener data.

// 中央事件总线
var bus = new Vue();

Vue.component("brother1", {
    data() {
        return {
            brother2Msg: ''
        }
    },
    template: `
        <div>
            <p>我是同级组件A</p>
            <p>同级组件B传递过来的数据:{{brother2Msg}}</p>
        </div>
    `,
    mounted() {
        // 绑定自定义的全局事件globalEvent
        bus.$on('globalEvent', (val)=>{
            this.brother2Msg = val;
        })
    }
});

Vue.component("brother2", {
    data() {
        return {
            msg: ""
        }
    },
    template: `
        <div>
            <p>我是同级组价B</p>
            <input type="text" v-model="msg" @input="passData(msg)"/>
        </div>
    `,
    methods: {
        passData(val){
            // 触发自定义的全局事件globalEvent
            bus.$emit('globalEvent', val)
        }
    }
});

var App = {  // 父组件
    template: `
        <div>
            <brother1></brother1>
            <brother2></brother2>
        </div>
    `
};

new Vue({
    el: "#app",
    components: {App},
    template: "<App/>"
})

4. Children $ $ parent and parent-child communication between components

By the parent component this.$children[<index>].<prop_name>data can be transferred to the subassembly; subassembly by this.parent.<prop_name>passing data to the parent component.

Vue.component("Child", {
    props: {
        value: String, //v-model会自动传递一个属性名为value的prop属性
    },
    data() {
        return {
            myMessage: this.value
        }
    },
    methods: {
        changeValue() {
            // 通过如此调用,可以向父组件传递数据,改变父组件的值
            this.$parent.message = this.myMessage;
        }
    },
    template: `
        <div>
            <input type="text" v-model="myMessage" @change="changeValue">
            <p>{{myMessage}}</p>
        </div>
    `
});

Vue.component('Parent', {
    data() {
        return {message: 'Hi, child'}
    },
    template: `
        <div>
            <p>我是父组件</p>
            <p>{{message}}</p>
            <button @click="changeChildValue">test</button>
            <Child></Child>
        </div>
    `,
    methods: {
        changeChildValue() {
            // 通过如此调用,可以向子组件传递数据,改变子组件的值
            this.$children[0].myMessage = this.message;
        }
    },
});

var App = {
    template: `
        <div>
            <h2>我是入口组件</h2>
            <Parent/>
        </div>
    `
};

new Vue({
    el: "#app",
    components: {App},
    template: "<App/>"
})

5. Use provide one-way communication and to inject achieved parent component subassembly

Parent components by provideproviding a variable, then the sub-assembly by injectinjected variable. No matter how deep sub-assemblies, as long as the call injectthen it can inject providedata, instead of being limited only from the current parent component propsto obtain data attributes. As long as the life cycle of the parent components, sub-assemblies can be called.

Vue.component("Child", {
    data() {
        return {msg: ""}
    },
    template: "<div>我是子组件: {{msg}}</div>",
    inject: ['for'],
    created() {
        this.msg = this.for;
    }
});

Vue.component("Parent", {
    template: `
        <div>
            <p>我是父组件</p>
            <Child/>
        </div>
    `
});

var App = {
    provide: {
        for: "从祖先组件跨代传递到子孙组件的数据"
    },
    template: `
        <div>
            <h2>我是入口组件,也是祖先组件</h2>
            <Parent/>
        </div>
    `
};

new Vue({
    el: "#app",
    components: {
        App
    },
    template: "<App/>"
})

Second, the filter

  • Filter action: be tampered data page.
  • Type filter: a local filter, global filters.

1. Local Filter

  • Disclaimer Filters: In assembly filters-defined function options.
  • Using a filter: {{data | myFilter}}

2. Global Filters

Use Vue.filter(<name>, func)to create global filters.

Vue.filter("moneyFormat", function(value) {
    return "¥" + value;
})

3. The filter parameters can also pass

Vue.filter("myFilter", function(value, arg) {
    return arg + value.split('').reverse().join('');
})

Third, the slot

Slot slotis Vuebuilt-in components, its role as a carrier of the content distribution outlet.

Named Slot

To slotadd a nameproperty called the slot named slot, in use, according to namereplace the contents to each.

Vue.component("myLi", {
    template: `
        <li>
            <slot name="one">第一个插槽</slot>
            <slot name="two">第二个插槽</slot>
        </li>
    `
});
new Vue({
    el: "#app",
    template: `
        <ul>
            <myLi>
                <h3 slot="two">插入第二插槽</h3>
                <h2 slot="one">插入第一插槽</h2>
            </myLi>
        </ul>
    `
})

Four, watch monitor

watchListening to a single attribute, when listening basic data types, the use of simple monitoring ; when monitoring complex data type (data type reference), using a depth monitor .

  • Defined watchwhen the monitor, watchthe attribute name of the object being monitored and must dataname the object data attributes the same .

Sample code:

new Vue({
    el: "#app",
    data: {
        msg: "",
        arr_obj: [
            {
                name: "Jack",
                age: 18,
                sex: male
            }
        ]
    },
    watch: {
        // 基本数据类型,简单监视
        msg: function(newValue, oldValue) {
            console.log(newValue, oldValue);
        },
        // 复杂数据类型,深度监视
        arr_obj: {
            deep: true,
            handler: function(newValue, oldValue) {
                console.log(newValue);
            }
        }
    }
})

Fifth, the calculation of property

Calculating a plurality of attribute data attributes can monitor simultaneously.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue-computed</title>
    <script src="node_modules/vue/dist/vue.js"></script>
    <style>
        .active{
            background-color: #409eff;
        }
    </style>
</head>
<body>
<div id="app">
    <audio autoplay controls :src="getCurrentMusicSrc"></audio>
    <ul>
        <li
            v-for="(item, index) in musicData"
            @click="playMusic(index)"
            :class="{active: currentIndex == index}">
            <h4>{{item.name}}</h4><span>--{{item.author}}</span>
        </li>
    </ul>
</div>

<script>
    var musicData = [
        {
            name: "起风了",
            author: "买辣椒也用券",
            songSrc: './Music/起风了.mp3'
        },
        {
            name: "芒种",
            author: "赵方婧",
            songSrc: './Music/芒种.mp3'
        },
        {
            name: "野狼disco",
            author: "宝石gem",
            songSrc: './Music/野狼disco.mp3'
        }
    ];
    new Vue({
        el: "#app",
        data: {
            musicData: musicData,
            currentIndex: 0
        },
        computed: {
            getCurrentMusicSrc(){
                return this.musicData[this.currentIndex].songSrc
            }
        },
        methods: {
            playMusic(index){
                this.currentIndex = index
            }
        }
    })
</script>
</body>
</html>

Sixth, the life cycle

Lifecycle hook function:

  1. beforeCreate: before the component is created, then the component object instance has been created, but the property has not been initialized instance.
  2. created: after the component is created, in this method will usually request the backend to retrieve data.
  3. beforeMount: Mount data to DOMbe called before.
  4. mounted: mount data to DOMlater calls, the application: operation DOM.
  5. beforeUpdate: update DOMbefore calls, application: You can obtain the original DOM.
  6. updated: update DOMlater calls, the application: You can get the latest DOM.
  7. activated: When keep-aliveinvoked when the component is activated.
  8. deactivated: When keep-aliveinvoked when the component is disabled.
  9. beforeDestroy: call before the component is destroyed.
  10. destroyed: Called after the destruction of the component.
  11. errorCaptured:

Seven, keep-alive built-in components

Vue built-in components keep-alivecan be retained in the assembly in the assembly state switching process in memory, i.e., cache component, rendering prevent duplication DOM.

var App = {
    data() {
        return {
            isShow: true
        }
    },
    template: `
        <div>
            <keep-alive>
                <sub-component v-if="isShow"></sub-component>
            </keep-alive>
            <button @click="isShow=!isShow">显示切换</button>
        </div>
    `
}

new Vue({
    el: "#app",
    components: {App}
})

Eight other supplements

  • If you give HTML tags binding ref="xxx"property, use this.$refs.xxxget native JS-DOMobjects.
  • If a component binding ref=“xxx”properties, so this.$refs.xxxget that this component objects.
  • $nextTick()Will DOMautomatically trigger the update after the end of the cycle, executes its callback function. This method must be used after modifying the data, it acquires its callback function after update DOM.
  • After obtaining updates DOM, in addition to use $nextTick(), you can also hook function in the life cycle updatedget in.
let App = {
    data() {
        return {
            isShow: false
        }
    },
    template: `
        <div class="app">
            <input type="text" v-show="isShow" ref="input" />
        </div>
    `,
    mounted() {
        this.isShow = true;
        /*this.$nextTick(function() {  // 通过$nextTick的回调函数获取DOM,并获取焦点
            this.$refs.input.focus();
        });*/
        this.$nextTick(()=>{  // 通过$nextTick定义回调函数为箭头函数,获取DOM,并获取焦点
            this.$refs.input.focus();
        })
    }
};

new Vue({
    el: "#app",
    template: "<App/>",
    components: {App}
})

Nine, RESTful specification

RESTful specification is a style of software architecture, design style, instead of the standard provides a set of design principles and constraints to interact with the client and server.
Separate front and rear ends:

  • Provide back-end interface (API)
  • The front page and write Ajax technology

1. Resource Oriented become

Each URL represents a resource, try not to use verbs in the URL, use nouns, nouns often corresponds with the database table. In general, the table in the database are the same kind collection of records, all in the API should also use the plural noun.
For example: a zoo to provide information API, including a variety of information of animals and employees, its path should be designed to:

https://api.example.com/v1/zoos
https://api.example.com/v1/animals
https://api.example.com/v1/employees

RESTful specification reference

2. In the URL filters

If a large number of records, the server can not all the data are returned to the user. API parameters should be provided for filtering return results.

?limit=10: 指定返回记录的数量
?offset=10: 指定返回记录的开始位置
?page=2&per_page=100: 指定第几页,以及每页的记录数
?sortby=name&order=asc: 指定返回结果按照哪个属性排序,以及排序顺序
?item_id=1: 指定筛选条件

3. Try to use HTTPS

4. When setting the respective status code

5. Return Error Message

If the status code is 4XX, you should return an error message to the user. In general, the information will be returned erroras the key name as a key to the error message.

6. Hypermedia API

If you encounter a situation you want to jump, then jump would carry interfaces URL.
Hypermedia API design, such as the github API is this design. Access api.github.com'll get a list of URLs of all available API.

7. Other

  1. API authentication should use OAuth 2.0 framework
  2. The server returns data formats, you should try to use JSON, avoid using XML

Guess you like

Origin www.cnblogs.com/Oliver-yzx/p/12129670.html