隨着 typescript 愈來愈受到前端框架的關注,最近使用 vue + typescript 作了一個項目。發現寫法與 vue + js 徹底不同。可是原理相同。接下來給你們介紹 Vue 開發中經常使用的傳值方式。css
Vue 經常使用的三種傳值方式有:前端
引用官網的一句話:父子組件的關係能夠總結爲 prop 向下傳遞,事件向上傳遞。父組件經過 prop 給子組件下發數據,子組件經過事件給父組件發送消息,以下圖所示:vue
// 父組件 <template> <div class="index"> <div>父組件: <input type="text" v-model="value"></div> <!-- 引入子組件 --> <About :value="value"/> </div> </template> <script lang="tsx" type="text/tsx"> import {Component, Prop, Vue} from "vue-property-decorator"; import About from "@/views/About.vue"; @Component({ // 引入子組件 components: { About } }) export default class HelloWorld extends Vue { value: string = "我是父組件哦"; created() { } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang="scss"></style>
子組件typescript
// 子組件 <template> <div class="about"> 子組件:<span>{{value}}</span> </div> </template> <script lang="tsx" type="text/tsx"> import {Component, Prop, Vue} from "vue-property-decorator"; @Component export default class About extends Vue { // 接受父組件的值 @Prop({ type: String, // 父組件傳遞給子組件的數據類型 required: false, // 是否必填 default: ' ' // 默認值, 若是傳入的是 Object,則要 default: ()=>({}) 參數爲函數 }) value !: string; created() {} } </script>
.
// 父組件 <template> <div class="index"> <div>父組件:{{msg}}</div> <!--bindSend 爲子組件 @Emit('bingSend') 裏面綁定的事件--> <About @bindSend="propMsg"/> </div> </template> <script lang="tsx" type="text/tsx"> import {Component, Vue} from "vue-property-decorator"; import About from "@/views/About.vue"; @Component({ components: { About } }) export default class HelloWorld extends Vue { msg: string = ''; created() {}; // 接收子組件發送數據是 觸發的事件 propMsg(msg: string){ this.msg = msg; } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang="scss"></style>
子組件bash
// 子組件 <template> <div class="about"> 子組件:個人子組件的數據 <button @click="propMsg">點擊給父組件發送數據</button> </div> </template> <script lang="tsx" type="text/tsx"> import {Component, Emit, Vue} from "vue-property-decorator"; @Component export default class About extends Vue { msg: string = '子組件的msg數據'; // bindSend 爲父組件引用子組件上 綁定的事件名稱 @Emit('bindSend') send(msg: string){}; // send 處理給父組件傳值的邏輯 created() {} // 經過觸發這個事件來處理髮送的內容數據的邏輯,而後執行 @Emit() 定義的 sen(msg: string){} 事件 propMsg(){ this.msg = '子組件的msg數據,被傳給了父組件'; this.send(this.msg) } } </script>
這裏咱們實現的思路是: (1)其中一個兄弟組件向父組件發送數據; (2)而後父組件再向另外一個兄弟組件傳值;前端框架
做者:平凡相戀
連接:https://juejin.im/post/5c55156f6fb9a049ef270541
來源:掘金
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。框架