vue的精彩之處在于其組件的可復用性.下面談談組件(component)如何從父元素獲取數據
模塊引用
首先說說,如何引用模塊
<div id="app"><my-component ></my-component>
</div>
<script src=“unpkg.com/vue/dist/vue.min.js”> </ script> // vue的CDN
<script>Vue.component('my-component',{ // 模塊的聲明,注意:一定要在Vue實例掛載之前template: '<div> {{ message }}</div>' // 模塊的模板, 用于替換<my-component>中的內容})var app = new Vue({el:"#app",})
</script>
此時,自定義模塊my-component就在父元素內了.
props
vue提供了一個props屬性,它的作用是將父元素的數據,正向傳遞給子模塊,例如:
// 改變<my-component>,將message數據(父元素)綁定到該模塊上
<div id = "app"><input type="text" v-model.lazy="msg" placeholder="你有什么想對我說"><my-component message="來自父元素的消息" :warning-one="msg"></my-component>
</div>
// 在模塊聲明中加一個props屬性,其值是一個數組,注意在<my-component>中的warning-one,對應到JS聲明中是warningOne(駝峰)
Vue.component('my-component',{props:[''message","warningOne"], // 繼承父元素的數據template:'<div> {{ message}}: {{warningOne}}</div>', // 模板用于顯示
});
var app= new Vue({el: "#app",data:{msg: ' '}
});
看下效果:
輸入:晚上一起看電影(在乎你)吧~
老規矩,整體代碼如下:
<!DOCTYPE html>
<html><head><meta charset="utf-8">
</head><body><div id="app"><input rtpe="text" v-model.lazy ="msg" placeholder="你有什么想對我說"><my-component message="來自父組件的消息" :warning-one="msg"></my-component></div><script src="https://unpkg.com/vue/dist/vue.min.js"></script><script >Vue.component('my-component',{props: ['message','warningOne'],template: '<div>{{ message }}: {{warningOne}}</div>'});var app = new Vue({el:"#app",data:{msg:''}})</script>
</body></html>