一.全局组件和局部组件全局注册的组件可以在全局使用;而局部注册的组件只能在其定义的实例内使用。
<div id="app"> <hello1></hello1> <world></world> </div> <script> Vue.component("hello1",{ template:"<div>这是全局化组件</div>" }); worldworld={ template:"<div>我是局部组件</div>" }; var vm=new Vue({ el:"#app", data:null, components:{ "world":worldworld } }); </script>
二.向组件传递数据和校验<div id="app"> <world v-bind:here="country" :prop-c="city"></world> </div> <script> worldworld={ template:"<div>here is {{ here }} {{ propC }}</div>", //props:["here"] //写法一:指明可向组件传值 here 这种写法不校验传入值的格式 props: { //写法二:指明可向组件传值 here,propA,propB,propC,propD,propE,propF 并校验格式 here:String, // 基础类型检测 (`null` 意思是任何类型都可以) propA: Number, // 多种类型 propB: [String, Number], // 必传且是字符串 propC: { type: String, required: true }, // 数字,有默认值 propD: { type: Number, default: 100 }, // 数组/对象的默认值应当由一个工厂函数返回 propE: { type: Object, default: function () { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator: function (value) { return value > 10 } } } }; var vm=new Vue({ el:"#app", data:{ country:"China", //vue2仅允父组件向子组件传值 (子组件要向父组件传值要用vuex) city:"Beijing" }, components:{ "world":worldworld } }); </script>
三.在组件中注册子组件<div id="app"> <p>我的位置是:</p> <location :country="country" :city="city"></location> </div> <script> var cityComponent={ template:"<div>this is {{ city }}</div>", props:["city"] }; var locationComponent= { template: `<div> <p>this is {{ country }}</p> <city :city="city"></city> </div>`, props: ["country","city"], components: { "city":cityComponent } }; var vm=new Vue({ el:"#app", data:{ country:"USA", city:"Washington D.C." }, components:{ "location":locationComponent } }); </script>
四.一个Vue定义的可以动态切换模板的组件component
<div id="app"> <p>component-一个Vue自定义的组件,使用它可以动态的切换模板。 </p> <component :is="whichTemplate" :count="count"></component> <button @click="next">下一个模板</button> </div> <script> var pA={ template:'<div>this is {{ name }} {{ count }}</div>', data:function () { return{ name:'pA' } }, props:["count"] }; var pB={ template:'<div>this is pB {{ count }}</div>', props:["count"] }; var pC={ template:'<div>this is pC {{ count }}</div>', props:["count"] }; var pD={ template:'<div>this is pD {{ count }}</div>', props:["count"] }; var vm=new Vue({ el:"#app", data:{ whichTemplate:'p0', count:0 }, methods:{ next:function () { var current=parseInt(this.whichTemplate.slice(1)); var next="p"+ ((current+1) % 4); this.whichTemplate=next; this.count++; } }, components:{ "p0":pA, "p1":pB, "p2":pC, "p3":pD } }); </script>
Vue2 组件
最新推荐文章于 2024-04-30 08:49:28 发布