<div id="app"> <my-component message="来自父组件的数据"></my-component> </div> <script> Vue.component(‘my-component‘,{ props:[‘message‘], template:‘<div>{{message}}</div>‘ }); var app=new Vue({ el:‘#app‘ }) </script>
解决html不区分大小写
warning-text/warningText
<div id="app"> <input type="text" v-model="parentMessage"> <mc :message="parentMessage"></mc> </div>
注意:
<mc message="parentMessage"></mc>
传递的仅仅是字符串,而不是数字或布尔值或数组或对象。
<div id="app"> <mc :init-count="1"></mc> </div> <script> Vue.component(‘mc‘,{ props:[‘initCount‘], template:‘<div>{{count}}</div>‘, data:function(){ return{ count:this.initCount } } }); </script>
<div id="app"> <mc :width="100"></mc> </div> <script> Vue.component(‘mc‘,{ props:[‘width‘], template:‘<div :style="style">content</div>‘, computed:{ style:function(){ return width:this.width+‘px‘ } } }) </script>
<script> Vue.component(‘mc‘,{ props:{ propA:Number, propB:[String,Number], propC:{ type:Boolean, default:true }, propD:{ type:Number, required:true }, propE:{ type:Array, default:function(){ return []; }, propF:{ validator:function(value){ return value>10; } } } }) </script>
<div id="app"> <p>total:{{total}}</p> <mc @increase="handleGetTotal" @reduce="handleGetTotal"></mc> </div> <script> Vue.component(‘mc‘,{ template:‘ <div> <button @click="handleIncrease">+1</button> <button @click="handleReduce">-1</button> </div>‘, data:function(){ return{ counter:0 } }, methods:{ handleIncrease:function(){ this.counter++; this.$emit(‘increase‘,this.counter); }, handleReduce:function(){ this.counter--; this.$emit(‘reduce‘,this.counter); } } }); var app=new Vue({ el:‘#app‘, data:{ total:0 }, methods:{ handleGetTotal:function(total){ this.total=total; } } }) </script>
<div id="app"> <p>total:{{total}}</p>
<mc v-model="total"></mc>
</div> <script> Vue.component(‘mc‘,{ template:‘<button @click="handleClick">+1</button>‘, data:function(){ return {counter:0} }, methods:{ handleClick:function(){ this.counter++; this.$emit(‘input‘,this.counter); } } }); var app=new Vue({ el:‘#app‘, data:{total:0} }) </script>
<div id="app"> <p>total:{{total}}</p> <mc v-model="total"></mc> <button @click="handleReduce">-1</button> </div> <script> Vue.component(‘mc‘,{ props:[‘value‘], template:‘<input :value="value" @input="updateValue">‘, methods:{ updateValue:function(event){ this.$emit(‘input‘,event.target.value); } } }); var app=new Vue({ el:‘#app‘, data:{total:0}, methods:{ handleReduce:function(){ this.total--; } } }) </script>
<div id="app"> {{message}} <mc></mc> </div> <script> var bus=new Vue(); Vue.component(‘mc‘,{ template:‘<button @click="handleEvent">传递事件</button>‘, methods:{ handleEvent:function(){ bus.$emit(‘on-message‘,‘来自组件mc的内容‘); } } }); var app=new Vue({ dl:‘#app‘, data:{message:‘‘}, mounted:function(){ var _this=this; bus.$on(‘on-message‘,function(msg){ _this.message=msg; } } }) </script>
原文:https://www.cnblogs.com/fishope/p/10930148.html