外部引入javascript
<link href="https://cdn.bootcss.com/animate.css/3.5.2/animate.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <script type="text/javascript" src="../js/vue-2.5.16.js"></script>
HTML部分css
<div class="container"> <!--動態數據綁定--> <my-info v-bind:data='msg' v-on:close='closeHandler'></my-info> <!--靜態數據綁定--> <my-info data="操做有誤"></my-info> </div>
script部分vue
<script type="text/javascript"> Vue.component('my-info',{ template:` <transition leave-active-class="animated fadeOutUpBig"> <div v-show='isShow' style="background:orange; color:#fff; padding:.5em 1em; border-radius:5px; margin:.5em 0; position:relative"> <i class="fa fa-info-circle"></i> <span>{{data}}</span> <i @click='close' class="fa fa-close" style="position:absolute; right: 1em; cursor:pointer"></i> </div> </transition> `, //注意:data必須是一個函數 data(){ return { isShow:true } }, props:['data'], methods:{ close(){ //子組件向父組件發射事件 this.$emit('close'); //關閉消息框 this.isShow = false; } }, }); new Vue({ el:'.container', data:{ msg:'添加失敗!' }, methods:{ closeHandler(){ console.log('關閉了'); } } }); </script>
效果java
組件的建立和註冊分紅3步:建立組件構造器,註冊組件,掛載做用域內實例化
例如:app
<div id="app"> <!-- 3. #app是Vue實例掛載的元素,應該在掛載元素範圍內使用組件--> <my-component></my-component> </div> <script> // 1.建立一個組件構造器 var myComponent = Vue.extend({ template: '<div>這是個人全局組件</div>' }) // 2.註冊組件,並指定組件的標籤,組件的HTML標籤爲<my-component> Vue.component('my-component', myComponent) new Vue({ el: '#app' }); </script>
咱們來理解組件的建立和註冊:函數
例如:this
<div id="app"> <!--該組件不會被渲染,而且報錯--> <my-component></my-component> </div> <div id="app1"> <my-component></my-component> </div> <script> new Vue({ el: "#app" }); Vue.component("my-component", { template: "<h1>這是個人全局組件</h1>" }); new Vue({ el: "#app1" }) </script>
組件實例的做用域是孤立的,父組件能夠經過props向下傳遞數據給子組件。spa
Prop靜態傳遞數據code
<div class="father"> <child msg="hello!" data="yes!"></child> </div> Vue.component('child',{ props:['msg',"data"], template:`<p>{{msg}}</p> <p>{{data}}</p> ` })
Prop動態傳遞數據component
<div class="father"> <child v-bind:msg="val"></child> </div> Vue.component('child',{ props:["msg"], template:` <p>{{msg}}</p>` }) new Vue({ el:'.father, data:{ val:'添加失敗!' } })