如何理解vue.js組件的作用域是獨立的


vue.js組件的作用域是獨立,可以從以下三個方面理解:

1、父組件模板在父組件作用域內編譯,父組件模板的數據用父組件內data數據;
2、子組件模板在子組件作用域內編譯,子組件模板的數據用子組件內data數據,如果要用父組件的必須用props傳遞;
3、子組件標簽的數據,使用父組件內的data數據

案例代碼:

1
2
3
4
5
6
7
8
9
<div id="demo">
    <my-component v-if="show" v-bind:my-message="message">
        <h2 v-if="show">{{message}}</h2>
    </my-component>
</div>
<template id="child-component">
    <h1>{{message}} {{myMessage}}</h1>
    <slot v-if="show">this is slot</slot>
</template>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var vm = new Vue({
    el : "#demo",
    data : {
        message : "vue",
        show : true
    },
    components : {
        "my-component" : {
            template : "#child-component",
            props : ["myMessage"],
            data : function(){
                return {
                    message : "vue1",
                    show : true
                }
            }
        }
    }
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM