VUEvue项目

Vue - Vue.extend() 和 extends

2019-11-05  本文已影响0人  ElricTang

一. 全局API:Vue.extend

使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。

    <body>
        <div id='app'></div>
        <script>
            let Com1 = Vue.extend({
                template:'<header>{{msg}}</header>',
                data(){
                    return {
                        msg:'hello world'
                    }
                }
            });
            new Com1().$mount('#app');
        </script>
    </body>

二. 组件选项 extends(可理解为单继承,只接受一个extends)

允许声明扩展另一个组件(可以是一个简单的选项对象或构造函数),而无需使用 Vue.extend。这主要是为了便于扩展单文件组件。

    <body>
        <div id='app'></div>
        <script>
            let father = {
                created(){
                    console.log('father的created()钩子')
                },
                data(){
                    return {
                        msg:'msg from father'
                    }             
                }
            }
            let child = new Vue({
                el:'#app',
                extends:father,
                data:{
                    msg:'msg from child' 
                },
                created(){
                    console.log('child的created钩子');
                    console.log(this.msg);
                }
            })
        </script>
    </body>
继承生命周期钩子
    <body>
        <div id='app'></div>
        <script>
            let father = {
                created(){
                    console.log('father的created()钩子')
                },
                data(){
                    return {
                        msg:'msg from father'
                    }             
                },
                methods:{
                    say(){
                        console.log('hello world');
                    }
                }
            }
            let child = new Vue({
                el:'#app',
                extends:father,
                created(){
                    console.log('child的created钩子');
                    console.log(this.msg);
                    this.say();
                }
            })
        </script>
    </body>
继承data和methods

extends使得组件能像面向对象变成一样便于拓展。

上一篇 下一篇

猜你喜欢

热点阅读