vue --- 从模块从父元素获取数据
生活随笔
收集整理的這篇文章主要介紹了
vue --- 从模块从父元素获取数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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: ' '} });看下效果:
輸入:晚上一起看電影(在乎你)吧~
老規矩,整體代碼如下:
總結
以上是生活随笔為你收集整理的vue --- 从模块从父元素获取数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件模式、GRASP原则,GoF设计模式
- 下一篇: html5倒计时秒杀怎么做,vue 设