vue組件之間數(shù)據(jù)傳遞的方法實例分析
本文實例分析了vue組件之間數(shù)據(jù)傳遞的方法。分享給大家供大家參考,具體如下:
1、props:父組件 -->傳值到子組件
app.vue是父組件 ,其它組件是子組件,把父組件值傳遞給子組件需要使用 =>props
在父組件(App.vue)定義一個屬性(變量)sexVal = '男' 把該值傳遞給 子組件(B.vue),如下:
App.vue
<template> <div id="app"> <!--<router-view></router-view>--> <parentTochild :sex="sexVal"></parentTochild> </div> </template> <script> import parentTochild from './components/B' export default { name: 'app', data: function () { return { sexVal:"女" } }, methods: { }, components: { parentTochild } } </script>
B.vue
<template> <div class="b_class"> <!--外邊只允許有一個跟元素--> <p>父組件傳值給子組件</p> <p>姓名:{{name}}</p> <p>年齡:{{age}}</p> <p>sex:{{sex}}</p> </div> </template> <script> export default { data: function () { return { name: 'zs', age: 22 } }, props:['sex'] } </script>
tips:
在父傳值給子組件使用屬性值:props; 理解成 “ 中介” 父組件綁定傳遞屬性值(:sex="sexval") 子組件 獲取屬性值 props['sex'] 會添加到data 對象中
2、$emit:子組件 -->傳值到父組件
在B.vue 子組件添加一個點擊事件為例子
@click="sendMs
<input type="button" @click="sendMsg" value="子組件值傳父組件">
在調用該函數(shù)后使用$emit方法傳遞參數(shù) (別名,在父組件作為事件名稱, 值);
methods: { sendMsg: function () { this.$emit('childMsg', '值來自---子組件值') } }
App.vue
在父組件中 使用該別名(作為事件名使用),調用方法 childEvent 返回子組件傳過來的值
<p>{{message}}</p> <!--<router-view></router-view>--> <parentTochild :sex="sexVal" @childMsg = "childEvent"></parentTochild>
data: function () { return { sexVal: "女", message: '' } }, methods: { childEvent: function (msg) { this.message = msg; // msg 來自子組件 } }
點擊 “按鈕”值會傳到 父組件中。 組件之間不能互相傳值。
希望本文所述對大家vue.js程序設計有所幫助。
- vue父子組件的數(shù)據(jù)傳遞示例
- Vue 父子組件的數(shù)據(jù)傳遞、修改和更新方法
- Vue表單類的父子組件數(shù)據(jù)傳遞示例
- Vue 父子組件數(shù)據(jù)傳遞的四種方式( inheritAttrs + $attrs + $listeners)
- vuejs父子組件之間數(shù)據(jù)交互詳解
- vue2.0父子組件間傳遞數(shù)據(jù)的方法
- Vue組件之單向數(shù)據(jù)流的解決方法
- vue兄弟組件傳遞數(shù)據(jù)的實例
- Vue.js路由組件vue-router使用方法詳解
- vue-router:嵌套路由的使用方法
- vue組件數(shù)據(jù)傳遞、父子組件數(shù)據(jù)獲取,slot,router路由功能示例
相關文章
Element-ui table中過濾條件變更表格內容的方法
下面小編就為大家分享一篇Element-ui table中過濾條件變更表格內容的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03