Vue項目中經常使用到組件之間的數值傳遞,實現的方法很多,但是原理上基本大同小異。
實現思路:
父 向 子 組件傳值:使用 props 屬性。( props 是property[屬性] 的復數簡寫 )
子 向 父 組件傳值:使用自定義事件。
一、父子組件單向傳值
1.1、父向子傳值
父向子組件傳值,子組件接收到數據之后,保存到自己的變量中。
- //父組件寫法
- <cld :numP="num" ></cld>
- //子組件定義以及數據
- components:{
- cld:{
- template:'#child',
- props:{
- numP:Number
- },
- }
- }
- //子組件內容
- <template id="child">
- <div>
- {{ numP }}
- </div>
- </template>
props 用于接收父組件傳過來的值,props 的寫法有很多種,具體如:
- //方式1 : 直接接收數據
- props: [ 'numP' ]
- //方式2: 加類型限制
- props: [
- numP: Number
- ]
- //方式3:添加默認值
- props: [
- numP: {
- type:Number,
- default:0
- }
- ]
- //方式4:是否必須值限制
- props: [
- numP: {
- type:Number,
- default:0,
- require:true //添加必須值,不傳此值會報錯
- }
- ]
- //方式5:采用對象形式
- props: {
- numP: {
- type:Number,
- default:0,
- }
- }
1.2、子向父傳值
子向父組件傳值,主要通過自定義事件進行傳值,具體實例如下:
- // 父組件內容
- <div>
- 子組件獲取到的數據{{getNum}}
- <cld :numb="num" @accept="getNumC"></cld>
- </div>
- //父組件方法
- methods:{
- getNumC(data){
- this.getNum = data //接收子組件傳的數據
- }
- },
- //子組件定義
- components:{
- cld:{
- template:'#child',
- data(){
- return{
- numC:1314 //子組件數據定義
- }
- },
- mounted(){
- this.$emit( 'accept' , this.numC ) // 觸發自定義事件
- }
- }
- },
二、父子組件數據雙向綁定
Vue 的數據都是單向流動的,而且 vue 中從來就沒有任何的雙向綁定,v-model 實現的雙向綁定只是語法糖而已。
方式1:利用 watch 實現父子組件的數據雙向綁定,具體實例如下:
- <div id="app">
- 數據<br>{{num}}
- <input type="text" v-model="num"><br>
- <cld :numb="num" @accept="getNumC"></cld>
- </div>
- //子組件內容
- <template id="child">
- <div>
- 數據<br>{{childNum}}
- <input type="text" v-model="childNum" />
- </div>
- </template>
- <!-- 父子組件通信 -->
- const app = new Vue({
- el:'#app',
- data:{
- num:'520',
- },
- methods:{
- getNumC(data){
- this.num = data
- }
- },
- components:{
- cld:{
- template:'#child',
- props:{
- numb:String
- },
- data(){
- return{
- childNum:0,
- }
- },
- watch:{
- numb:function(){
- this.childNum = this.numb
- },
- childNum:function(){
- this.$emit('accept',this.childNum)
- }
- },
- mounted(){
- this.childNum = this.numb
- }
- }
- }
- })
方式2:.sync 修飾符實現雙向綁定
在vue 1.x 中的 .sync 修飾符所提供的功能。當一個子組件改變了一個帶 .sync 的 prop 的值時,這個變化也會同步到父組件中所綁定的值。這很方便,但也會導致問題,因為它破壞了單向數據流。(數據自上而下流,事件自下而上走)
- <cld :numb.sync="num" ></cld>
- //會擴展為:
- <cld :numb="bar" @update:numb=”val => bar = val”/>
當組件需要更新 numb 的值時,需要觸發更新事件:
- this.$emit("update:numb", newValue );
使用具體實例如下:
- // 父組件
- <Father :foo.sync="foo"></Father>
- //子組件
- props: ['foo'],
- data() {
- return {
- newFoo: this.foo;
- }
- },
- methods:{
- add:function(){
- this.newMsg=10;
- this.$emit('update:foo',this.newFoo);
- }
- }
原文鏈接:https://www.toutiao.com/a7005375174686114340/