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: "数据: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: "数据:18892087118" } } }; var CHILD = { template: "#child", data: function() { return { name: "子组件", cmsg: "子组件里的第一个数据", cmsgtwo: "子组件里的第二个数据" } }, methods: { change: function() { this.fromfather.fmsg = "子组件数据被更改了" } }, mounted: function() { this.cmsg = this.fromfather; }, props: ["fromfather"], }; // 注册组件 Vue.component('father', FATHER); Vue.component("child", CHILD); var vm = new Vue({ data: { fmsg: "data里的数据", giveData: { fmsg: "这是父组件里的数据" } }, methods: {}, // 局部组件fatherlocal components: { 'fatherlocal': { template: '#father-local', data: function() { return { name: "局部-父组件", data: "局部-父组件里的数据" } } } } }).$mount('#app'); </script> </body> </html>
新闻热点
疑难解答
图片精选