1、組件聲明
<!-- 全局組件模板father模板 --> <template id="father"> <div> <h3>這是{{name}}</h1> <div> <p>這是{{data}}</p> </div> </div> </template> var FATHER = { template: "#father", data: function() { return { name: "一個全局組件-模板-", data: "數(shù)據(jù):18892087118" } } }; 2、組件注冊
Vue.component('father', FATHER); 3、組件掛載
<h5>全局組件1</h5> <father></father>
4、組件實例
<!DOCTYPE html> <html> <head> <title>vue2.0 --- 局部組件與全局組件</title> </head> <body> <h3>vue2.0局部組件與全局組件</h3> <div id='app'> <h5>局部組件</h5> <fatherlocal></fatherlocal> <hr> <h5>全局組件1</h5> <father></father> <hr> <h5>全局組件2</h5> <child :fromfather='giveData'></child> </div> <!-- 局部組件模板fatherlocal --> <template id="father-local"> <div> <h3>這是{{name}}</h1> <div> <p>這是{{data}}</p> </div> </div> </template> <!-- 全局組件模板father --> <template id="father"> <div> <h3>這是{{name}}</h1> <div> <p>這是{{data}}</p> </div> </div> </template> <template id="child"> <div> <h3>這是{{name}}</h3> <div> <p>{{cmsgtwo}}</p> <p>{{cmsg}}</p> <p>{{fromfather}}</p> <p>{{fromfather.fmsg}}</p> <p><input type="button" value="按鈕" @click=" "></p> </div> </div> </template> <script src="vue_2.2.2_vue.min.js"></script> <script type="text/javascript"> // 定義組件 var FATHER = { template: "#father", data: function() { return { name: "一個全局組件-模板-", data: "數(shù)據(jù):18892087118" } } }; var CHILD = { template: "#child", data: function() { return { name: "子組件", cmsg: "子組件里的第一個數(shù)據(jù)", cmsgtwo: "子組件里的第二個數(shù)據(jù)" } }, methods: { change: function() { this.fromfather.fmsg = "子組件數(shù)據(jù)被更改了" } }, mounted: function() { this.cmsg = this.fromfather; }, props: ["fromfather"], }; // 注冊組件 Vue.component('father', FATHER); Vue.component("child", CHILD); var vm = new Vue({ data: { fmsg: "data里的數(shù)據(jù)", giveData: { fmsg: "這是父組件里的數(shù)據(jù)" } }, methods: {}, // 局部組件fatherlocal components: { 'fatherlocal': { template: '#father-local', data: function() { return { name: "局部-父組件", data: "局部-父組件里的數(shù)據(jù)" } } } } }).$mount('#app'); </script> </body> </html>
新聞熱點
疑難解答
圖片精選