溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

淺談Vue父子組件和非父子組件傳值問題

發(fā)布時(shí)間:2020-09-16 12:22:20 來源:腳本之家 閱讀:136 作者:wl_xiaowangzi 欄目:web開發(fā)

本文介紹了淺談Vue父子組件和非父子組件傳值問題,分享給大家,具體如下:

1.如何創(chuàng)建組件

1.新建一個(gè)組件,如:在goods文件夾下新建goodsList.vue

<template>
  <div class='tmpl'>
    goodsList組件
  </div>
</template>

<style>

</style>

<script>

  export default {
    data() {
      return{}
    },
    created() {

    },
    methods: {

    },
    components:{

    }
  }
</script>

2.在main.js中引入 import goodsList from 'goods/goodsList.vue'

3.在main.js中創(chuàng)建路由對象,創(chuàng)建路由規(guī)則

const router = new VerRouter({
  routes[
    {path:/goods/goodsList,component:goodsList}
  ]
})

4.在主組件App.vue中設(shè)置 <router-link to="/goods/goodsList">商品列表</router-link>

系統(tǒng)會自動(dòng)幫我們把這個(gè)標(biāo)簽轉(zhuǎn)化為a標(biāo)簽href="#/goods/goodsList" rel="external nofollow"

2.如何在父組件中嵌入子組件

1.新建一個(gè)子組件 subcomponent.vue

2.在父組件中引入 import subComponent from '../subComponent/subcomponent.vue'

3.在父組件中注冊 components

 export default {
    components:{
      //如果屬性名和值相同,可以簡寫
      subComponent
    }
  }

4.在父組件指定位置寫一個(gè)自定義標(biāo)簽<subComponent></subComponent>

3.如何實(shí)現(xiàn)父子組件之間的傳值

1.父組件向子組件傳值

1.在子組件中設(shè)置props:['commentId'] //子組件用來接收父組件傳遞過來值的屬性名稱

2.在父組件的自定義子組件標(biāo)簽中設(shè)置<subComponent :commentId="this.$route.params.photoId"></subComponent>//父組件傳遞值給子組件

2.子組件向父組件傳值

1.在父組件的自定義標(biāo)簽中設(shè)置一個(gè)自定義函數(shù)<subComponent v-on:paramsChange="getSubComponentParams"></subComponent>

2.在父組件的methods中聲明函數(shù)

  getSubComponentParams(params){
  //接收來自子組件的參數(shù)params
    this.myParams = params;
  }

3.在子組件中傳遞參數(shù)

  /**
  * 參數(shù)1:要觸發(fā)的事件名稱
  * 參數(shù)2:傳遞的值
  */
  this.$emit('paramsChange',this.params)

如何實(shí)現(xiàn)非父子組件的傳值

非父子組件中兩個(gè)組件沒有聯(lián)系,不能使用this來傳值,所以我們只能通過第三方的變量,來達(dá)到傳值的效果,這個(gè)第三方變量就是:

使用一個(gè)空的 Vue 實(shí)例作為中央事件總線

傳值步驟:

1.創(chuàng)建一個(gè)公用js組件 在組件內(nèi)導(dǎo)出一個(gè)空的Vue實(shí)例,比如新建一個(gè)commonvue.js文件

import Vue from 'vue'

export default new Vue() //es6的寫法
/**
 * 相當(dāng)于下面這樣寫
 * 
 * const bus = new Vue()
 * module.exports = bus
 */

2.在組件A中傳遞參數(shù)

bus.$emit('goodsCount',this.myCount)

3.在組件B中接收參數(shù)

bus.$on('goodsCount',(goodsCount)=>{
   const oldVal = $("#badgeId").text()

   const lastVal = parseInt(oldVal) + goodsCount
   console.log(lastVal)
   $("#badgeId").text(lastVal)
 })

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI