[Vue]组件实例对象可以访问到Vue原型上的属性、方法

发布时间 2023-11-03 09:24:46作者: 夕苜19
 
    1. 一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype
    2. 为什么要有这个关系:让组件实例对象vc可以访问到Vue原型上的属性、方法
<body>
    <div id="root"></div>
</body>
<script>
    let school = Vue.extend({
        template: `
        <div>
            <h2>学校:{{ name }}</h2>
            <h2>地址:{{ address }}</h2>
            <button @click='show_x'>点我看看x</button>
        </div>
        `,
        data() {
            return {
                name: '南方开心大学',
                address: '天津市'
            }
        },
        methods: {
            show_x() {
                alert(this.x)
            }
        }
    })
    let vm = new Vue({
        template: `
        <school></school>
        `,
        el: '#root',
        components: { school }
    })

    Vue.prototype.x = 99
    console.log(school.prototype.__proto__ === Vue.prototype)  // true
    console.log(vm.x)                                          // 99
    console.log(school.prototype.x)                            // 99
</script>