vuejs中父子組件之間通信方法實(shí)例詳解
本文實(shí)例講述了vuejs中父子組件之間通信方法。分享給大家供大家參考,具體如下:
一、父組件向子組件傳遞消息
// Parent.vue
<template>
<div class="parent">
<v-child :msg="message"></v-child>
</div>
</template>
<script>
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
// 父組件將message作為參數(shù)傳入子組件中
message: '來(lái)自父組件消息'
}
}
}
</script>
// Child.vue
<template>
<div class="child">
<h1>child</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
// 通過(guò)props定義外部系統(tǒng)可以傳入的參數(shù)
// 定義了一個(gè)msg變量,類型是String,默認(rèn)是空字符串
props: {
msg: {
type: String,
default: ""
}
}
}
</script>
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Parent from '@/test/Parent'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/parent',
component: Parent
}
]
})
二、子組件向父組件傳遞消息
// Parent.vue
<template>
<div class="parent">
<v-child :msg="message" @childNotify="childNotify"></v-child>
</div>
</template>
<script>
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
// 父組件將message作為參數(shù)傳入子組件中
message: '來(lái)自父組件消息'
}
},
methods: {
childNotify (params) {
console.log(params)
}
}
}
</script>
// Child.vue
<template>
<div class="child" @click="notifyParent">
<h1>child</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
// 通過(guò)props定義外部系統(tǒng)可以傳入的參數(shù)
// 定義了一個(gè)msg變量,類型是String,默認(rèn)是空字符串
props: {
msg: {
type: String,
default: ""
}
},
methods: {
notifyParent () {
var params = {
m: 1,
n: 2
}
// 子組件以事件的形式通知父組件(需要使用$emit方法,第一個(gè)參數(shù),事件名稱;第二個(gè)事件附帶的參數(shù))
this.$emit('childNotify', params)
}
}
}
</script>
參考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html
希望本文所述對(duì)大家vue.js程序設(shè)計(jì)有所幫助。
相關(guān)文章
vue指令只能輸入正數(shù)并且只能輸入一個(gè)小數(shù)點(diǎn)的方法
這篇文章主要介紹了vue指令只能輸入正數(shù)并且只能輸入一個(gè)小數(shù)點(diǎn)的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
jdk1.8+vue elementui實(shí)現(xiàn)多級(jí)菜單功能
這篇文章主要介紹了jdk1.8+vue elementui實(shí)現(xiàn)多級(jí)菜單功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
解決elementui上傳組件el-upload無(wú)法第二次上傳問(wèn)題
這篇文章主要介紹了解決elementui上傳組件el-upload無(wú)法第二次上傳問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
實(shí)例詳解vue.js淺度監(jiān)聽(tīng)和深度監(jiān)聽(tīng)及watch用法
這篇文章主要介紹了vue.js淺度監(jiān)聽(tīng)和深度監(jiān)聽(tīng)及watch用法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-08-08
使用vue-cli打包過(guò)程中的步驟以及問(wèn)題的解決
這篇文章主要介紹了使用vue-cli打包過(guò)程中的步驟以及問(wèn)題的解決,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
基于vue+echarts數(shù)據(jù)可視化大屏展示的實(shí)現(xiàn)
這篇文章主要介紹了基于vue+echarts數(shù)據(jù)可視化大屏展示的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

