淺談Vue父子組件和非父子組件傳值問題
本文介紹了淺談Vue父子組件和非父子組件傳值問題,分享給大家,具體如下:
1.如何創(chuàng)建組件
1.新建一個組件,如:在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中設置 <router-link to="/goods/goodsList">商品列表</router-link>
系統(tǒng)會自動幫我們把這個標簽轉(zhuǎn)化為a標簽href="#/goods/goodsList" rel="external nofollow"
2.如何在父組件中嵌入子組件
1.新建一個子組件 subcomponent.vue
2.在父組件中引入 import subComponent from '../subComponent/subcomponent.vue'
3.在父組件中注冊 components
export default { components:{ //如果屬性名和值相同,可以簡寫 subComponent } }
4.在父組件指定位置寫一個自定義標簽<subComponent></subComponent>
3.如何實現(xiàn)父子組件之間的傳值
1.父組件向子組件傳值
1.在子組件中設置props:['commentId'] //子組件用來接收父組件傳遞過來值的屬性名稱
2.在父組件的自定義子組件標簽中設置<subComponent :commentId="this.$route.params.photoId"></subComponent>//父組件傳遞值給子組件
2.子組件向父組件傳值
1.在父組件的自定義標簽中設置一個自定義函數(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)
如何實現(xiàn)非父子組件的傳值
非父子組件中兩個組件沒有聯(lián)系,不能使用this來傳值,所以我們只能通過第三方的變量,來達到傳值的效果,這個第三方變量就是:
使用一個空的 Vue 實例作為中央事件總線
傳值步驟:
1.創(chuàng)建一個公用js組件 在組件內(nèi)導出一個空的Vue實例,比如新建一個commonvue.js文件
import Vue from 'vue' export default new Vue() //es6的寫法 /** * 相當于下面這樣寫 * * 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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue刷新頁面時去閃爍提升用戶體驗效果的實現(xiàn)方法
這篇文章主要介紹了vue刷新頁面時去閃爍提升體驗方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-12-12簡易Vue評論框架的實現(xiàn)(父組件的實現(xiàn))
本篇文章主要介紹了簡易 Vue 評論框架的實現(xiàn)(父組件的實現(xiàn)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01vite項目添加eslint?prettier及husky方法實例
這篇文章主要為大家介紹了vite項目添加eslint?prettier及實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07解決vue數(shù)據(jù)更新但table內(nèi)容不更新的問題
這篇文章主要給大家介紹了vue數(shù)據(jù)更新table內(nèi)容不更新解決方法,文中有詳細的代碼示例供大家作為參考,感興趣的同學可以參考閱讀一下2023-08-08