欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

超實(shí)用vue中組件間通信的6種方式(最新推薦)

 更新時(shí)間:2022年11月06日 11:33:41   作者:Jiang_JY  
組件是 vue.js最強(qiáng)大的功能之一,而組件實(shí)例的作用域是相互獨(dú)立的,這就意味著不同組件之間的數(shù)據(jù)無法相互進(jìn)行直接的引用,所以組件間的相互通信是非常重要的,這篇文章主要介紹了vue中組件間通信的6種方式,需要的朋友可以參考下

前言

組件是 vue.js最強(qiáng)大的功能之一,而組件實(shí)例的作用域是相互獨(dú)立的,這就意味著不同組件之間的數(shù)據(jù)無法相互進(jìn)行直接的引用,所以組件間的相互通信是非常重要的。

除了使用vuex外還有下面6種組件間的通信方式:

1、 props / $emit

父組件通過 props 向子組件傳遞數(shù)據(jù),子組件通過 $emit 和父組件通信

(1)父組件向子組件傳值(props的用法)

props的特點(diǎn):

  • props只能是父組件向子組件進(jìn)行傳值,props使得父子組件之間形成一個(gè)單向的下行綁定。子組件的數(shù)據(jù)會(huì)隨著父組件的更新而響應(yīng)式更新。
  • props可以顯示定義一個(gè)或一個(gè)以上的數(shù)據(jù),對(duì)于接收的數(shù)據(jù),可以是各種數(shù)據(jù)類型,同樣也可以是傳遞一個(gè)函數(shù)。
  • props屬性名規(guī)則:若在props中使用駝峰形式,模板中標(biāo)簽需要使用短橫線的形式來書寫。

用法:

父組件:

// 父組件
<template>
    <div id="father">
        <son :msg="msgData" :fn="myFunction"></son>
    </div>
</template>

<script>
import son from "./son.vue";
export default {
    name: father,
    data() {
        msgData: "父組件數(shù)據(jù)";
    },
    methods: {
        myFunction() {
            console.log("vue");
        }
    },
    components: {
        son
    }
};
</script>

子組件:

// 子組件
<template>
    <div id="son">
        <p>{{msg}}</p>
        <button @click="fn">按鈕</button>
    </div>
</template>
<script>
export default {
    name: "son",
    props: ["msg", "fn"]
};
</script>

(2)子組件向父組件傳遞數(shù)據(jù)($emit的用法)

$emit的特點(diǎn):

  • $emit 綁定一個(gè)自定義事件,當(dāng)這個(gè)事件被執(zhí)行的時(shí)候就會(huì)將參數(shù)傳遞給父組件,而父組件通過v-on監(jiān)聽并接收參數(shù)

用法:

父組件:

// 父組件
<template>
  <div class="section">
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
    <p>{{currentIndex}}</p>
  </div>
</template>

<script>
import comArticle from './test/article.vue'
export default {
  name: 'comArticle',
  components: { comArticle },
  data() {
    return {
      currentIndex: -1,
      articleList: ['紅樓夢(mèng)', '西游記', '三國演義']
    }
  },
  methods: {
    onEmitIndex(idx) {
      this.currentIndex = idx
    }
  }
}
</script>

子組件:

//子組件
<template>
  <div>
    <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
  </div>
</template>

<script>
export default {
  props: ['articles'],
  methods: {
    emitIndex(index) {
      this.$emit('onEmitIndex', index) // 觸發(fā)父組件的方法,并傳遞參數(shù)index
    }
  }
}
</script>

2、ref / $refs

這種方式也是實(shí)現(xiàn)父子組件之間的通信

ref:這個(gè)屬性用在子組件上,它的用用就指向了子組件的實(shí)例,可以通過實(shí)例來訪問組件的數(shù)據(jù)和方法

用法:

在子組件中:

export default {
  data () {
    return {
      name: 'JavaScript'
    }
  },
  methods: {
    sayHello () {
      console.log('hello')
    }
  }
}

在父組件中:

<template>
  <child ref="child"></component-a>
</template>
<script>
  import child from './child.vue'
  export default {
    components: { child },
    mounted () {
      console.log(this.$refs.child.name);  // JavaScript
      this.$refs.child.sayHello();  // hello
    }
  }
</script>

3、eventBus事件總線($emit / $on)

eventBus事件總線適用于父子組件、非父子組件等之間的通信,使用步驟如下:

(1)創(chuàng)建事件中心管理組件之間的通信

// event-bus.js

import Vue from 'vue'
export const EventBus = new Vue()

(2)發(fā)送事件 假設(shè)有兩個(gè)兄弟組件firstCom和secondCom:

firstCom和secondCom的父組件:

<template>
  <div>
    <first-com></first-com>
    <second-com></second-com>
  </div>
</template>

<script>
import firstCom from './firstCom.vue'
import secondCom from './secondCom.vue'
export default {
  components: { firstCom, secondCom }
}
</script>

在firstCom組件中發(fā)送事件:

<template>
  <div>
    <button @click="add">加法</button>    
  </div>
</template>

<script>
import {EventBus} from './event-bus.js' // 引入事件中心

export default {
  data(){
    return{
      num:0
    }
  },
  methods:{
    add(){
      EventBus.$emit('addition', {
        num:this.num++
      })
    }
  }
}
</script>

(3)接收事件

在secondCom組件中接收事件:

<template>
  <div>求和: {{count}}</div>
</template>

<script>
import { EventBus } from './event-bus.js'
export default {
  data() {
    return {
      count: 0
    }
  },
  mounted() {
    EventBus.$on('addition', param => {
      this.count = this.count + param.num;
    })
  }
}
</script>

在上述代碼中,這就相當(dāng)于將num值存貯在了事件總線中,在其他組件中可以直接訪問。事件總線就相當(dāng)于一個(gè)橋梁,不用組件通過它來通信。雖然看起來比較簡(jiǎn)單,但是這種方法也有不變之處,如果項(xiàng)目過大,使用這種方式進(jìn)行通信,后期維護(hù)起來會(huì)很困難。

4、依賴注入(provide / inject)

這種方式就是vue中依賴注入,該方法用于 父子組件之間 的通信。當(dāng)然這里所說的父子不一定是真正的父子,也可以是祖孫組件,在層數(shù)很深的情況下,可以使用這種方式來進(jìn)行傳值。就不用一層一層的傳遞數(shù)據(jù)了。

provide和inject是vue提供的兩個(gè)鉤子,和data、methods是同級(jí)的。并且provide的書寫形式和data一樣。

  • provide 鉤子用來發(fā)送數(shù)據(jù)或方法。
  • inject鉤子用來接收數(shù)據(jù)或方法

用法:

父組件中:

provide() { 
    return {     
        num: this.num  
    };
}

子組件中:

inject: ['num']

還有另一種寫法,這種寫法可以訪問父組件中的所有屬性:

provide() {
 return {
    app: this
  };
}
data() {
 return {
    num: 1
  };
}

inject: ['app']
console.log(this.app.num)

注意: 依賴注入所提供的屬性是非響應(yīng)式的。

5、$parent / $children

  • 使用$parent可以讓組件訪問父組件的實(shí)例(訪問的是上一級(jí)父組件的屬性和方法)。
  • 使用 $children 可以讓組件訪問子組件的實(shí)例,但是, $children 并不能保證順序,并且訪問的數(shù)據(jù)也不是響應(yīng)式的。

用法:

子組件中:

<template>
  <div>
    <span>{{message}}</span>
    <p>獲取父組件的值為:  {{parentVal}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Vue'
    }
  },
  computed:{
    parentVal(){
      return this.$parent.msg;
    }
  }
}
</script>

父組件中:

<template>
  <div class="hello_world">
    <div>{{msg}}</div>
    <child></child>
    <button @click="change">點(diǎn)擊改變子組件值</button>
  </div>
</template>

<script>
import child from './child.vue'
export default {
  components: { child },
  data() {
    return {
      msg: 'Welcome'
    }
  },
  methods: {
    change() {
      // 獲取到子組件
      this.$children[0].message = 'JavaScript'
    }
  }
}
</script>

在上面的代碼中,子組件獲取到了父組件的parentVal值,父組件改變了子組件中message的值。

注意

  • 通過 $parent 訪問到的是上一級(jí)父組件的實(shí)例,可以使用 $root 來訪問根組件的實(shí)例
  • 在組件中使用$children拿到的是所有的子組件的實(shí)例,它是一個(gè)數(shù)組,并且是無序的
  • 在根組件 #app 上拿 $parent 得到的是 new Vue()的實(shí)例,在這實(shí)例上再拿 $parent 得到的是undefined,而在最底層的子組件拿 $children 是個(gè)空數(shù)組
  • $children 的值是數(shù)組,而 $parent是個(gè)對(duì)象

6、$attrs / $listeners

考慮一種場(chǎng)景,如果A是B組件的父組件,B是C組件的父組件。如果想要組件A給C組件傳遞數(shù)據(jù),這種隔代傳數(shù)據(jù)的情況該使用哪種方式呢?

如果是用props/ $emit 來一級(jí)一級(jí)的傳遞,確實(shí)可以完成,但是比較復(fù)雜;如果使用事件總線,在多人開發(fā)或者項(xiàng)目較大的時(shí)候,維護(hù)起來很麻煩;如果使用vuex,如果僅僅是傳遞數(shù)據(jù),那可能有點(diǎn)浪費(fèi)了。

針對(duì)上述情況,vue引入了 $attrs / $listeners,實(shí)組件之間的跨代通信。

  • $attrs:繼承所有的父組件屬性(除了props傳遞的屬性、class 和 style),一般用在子組件的子元素上
  • $listeners:該屬性是一個(gè)對(duì)象,里面包含了作用在這個(gè)組件上的所有監(jiān)聽器,可以配合 v-on=" $listeners " 將所有的事件監(jiān)聽器指向這個(gè)組件的某個(gè)特定的子元素。(相當(dāng)于子組件繼承父組件的事件)

再說一下 inheritAttrs

  • 默認(rèn)值為true,繼承所有的父組件屬性除props之外的所有屬性。
  • 只繼承class屬性。

$attrs / $listeners的用法:
A組件(APP.vue):

<template>
    <div id="app">
        //此處監(jiān)聽了兩個(gè)事件,可以在B組件或者C組件中直接觸發(fā) 
        <child1 :p-child1="child1" :p-child2="child2" @test1="onTest1" @test2="onTest2"></child1>
    </div>
</template>
<script>
import Child1 from './Child1.vue';
export default {
    components: { Child1 },
    methods: {
        onTest1() {
            console.log('test1 running');
        },
        onTest2() {
            console.log('test2 running');
        }
    }
};
</script>

B組件(Child1.vue):

<template>
    <div class="child-1">
        <p>props: {{pChild1}}</p>
        <p>$attrs: {{$attrs}}</p>
        <child2 v-bind="$attrs" v-on="$listeners"></child2>
    </div>
</template>
<script>
import Child2 from './Child2.vue';
export default {
    props: ['pChild1'],
    components: { Child2 },
    inheritAttrs: false,
    mounted() {
        this.$emit('test1'); // 觸發(fā)APP.vue中的test1方法
    }
};
</script>

C 組件 (Child2.vue):

<template>
    <div class="child-2">
        <p>props: {{pChild2}}</p>
        <p>$attrs: {{$attrs}}</p>
    </div>
</template>
<script>
export default {
    props: ['pChild2'],
    inheritAttrs: false,
    mounted() {
        this.$emit('test2');// 觸發(fā)APP.vue中的test2方法
    }
};
</script>

在上述代碼中:

  • C組件中能直接觸發(fā)test的原因在于 B組件調(diào)用C組件時(shí) 使用 v-on 綁定了$listeners 屬性
  • 在B組件中通過v-bind 綁定$attrs屬性,C組件可以直接獲取到A組件中傳遞下來的props(除了B組件中props聲明的)

總結(jié)

根據(jù)以上對(duì)這6種組件間的通信方法,可以將不同組件間的通信分為4種類型:父子組件間通信、跨代組件間通信、兄弟組件間通信、任意組件間通信

1、父子組件間通信

  • 子組件通過 props 屬性來接受父組件的數(shù)據(jù),然后父組件在子組件上注冊(cè)監(jiān)聽事件,子組件通過 emit 觸發(fā)事件來向父組件發(fā)送數(shù)據(jù)。
  • 通過 ref 屬性給子組件設(shè)置一個(gè)名字。父組件通過 $refs 組件名來獲得子組件,子組件通過 $parent 獲得父組件,這樣也可以實(shí)現(xiàn)通信。
  • 使用 provide/inject,在父組件中通過 provide提供變量,在子組件中通過 inject 來將變量注入到組件中。不論子組件有多深,只要調(diào)用了 inject 那么就可以注入 provide中的數(shù)據(jù)。

2、跨代組件間通信

  • 跨代組件間通信其實(shí)就是多層的父子組件通信,同樣可以使用上述父子組件間通信的方法,只不過需要多層通信會(huì)比較麻煩。
  • 使用上述的6種方法的$attrs / $listeners方法。

3、兄弟組件間通信

  • 通過 $parent + $refs 以父組件為中間人來獲取到兄弟組件,也可以進(jìn)行通信。

4、任意組件間通信

  • 使用 eventBus ,其實(shí)就是創(chuàng)建一個(gè)事件中心,相當(dāng)于中轉(zhuǎn)站,可以用它來傳遞事件和接收事件。它的本質(zhì)是通過創(chuàng)建一個(gè)空的 Vue 實(shí)例來作為消息傳遞的對(duì)象,通信的組件引入這個(gè)實(shí)例,通信的組件通過在這個(gè)實(shí)例上監(jiān)聽和觸發(fā)事件,來實(shí)現(xiàn)消息的傳遞。

如果業(yè)務(wù)邏輯復(fù)雜,很多組件之間需要同時(shí)處理一些公共的數(shù)據(jù),這個(gè)時(shí)候采用上面這一些方法可能不利于項(xiàng)目的維護(hù)。這個(gè)時(shí)候可以使用 vuex ,vuex 的思想就是將這一些公共的數(shù)據(jù)抽離出來,將它作為一個(gè)全局的變量來管理,然后其他組件就可以對(duì)這個(gè)公共數(shù)據(jù)進(jìn)行讀寫操作,這樣達(dá)到了解耦的目的。

到此這篇關(guān)于vue中組件間通信的6種方式的文章就介紹到這了,更多相關(guān)vue組件間通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論