Vue 2.0 typescript 寫法傳值方式:
隨着 typescript 越來越受到前端框架的關注,最近使用 vue + typescript 做了一個項目。發現寫法與 vue + js 完全不一樣。但是原理相同。接下來給大家介紹 Vue 開發中常用的傳值方式。
Vue 常用的三種傳值方式有:
- 父傳子
- 子傳父
- 非父子傳值
引用官網的一句話:父子組件的關系可以總結為 prop 向下傳遞,事件向上傳遞。父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息,如下圖所示:

接下來,我們通過實例來看可能會更明白一些:
1. 父組件向子組件進行傳值
父組件
// 父組件 <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>
子組件
// 子組件 <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>
2. 子組件向父組件傳值

父組件
.
// 父組件 <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>
子組件
// 子組件 <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>
3. 兄弟組件向傳值
這里我們實現的思路是: (1)其中一個兄弟組件向父組件發送數據; (2)然后父組件再向另一個兄弟組件傳值;
作者:平凡相戀
鏈接:https://juejin.im/post/5c55156f6fb9a049ef270541
來源:掘金
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
