vuejs中父子組件之間通信方法實例詳解
更新時間:2020年01月17日 10:36:45 作者:林飛的夢囈
這篇文章主要介紹了vuejs中父子組件之間通信方法,結合實例形式詳細分析了vue.js父組件向子組件傳遞消息以及子組件向父組件傳遞消息具體操作實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了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: '來自父組件消息'
}
}
}
</script>
// Child.vue
<template>
<div class="child">
<h1>child</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
// 通過props定義外部系統(tǒng)可以傳入的參數(shù)
// 定義了一個msg變量,類型是String,默認是空字符串
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: '來自父組件消息'
}
},
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 {
// 通過props定義外部系統(tǒng)可以傳入的參數(shù)
// 定義了一個msg變量,類型是String,默認是空字符串
props: {
msg: {
type: String,
default: ""
}
},
methods: {
notifyParent () {
var params = {
m: 1,
n: 2
}
// 子組件以事件的形式通知父組件(需要使用$emit方法,第一個參數(shù),事件名稱;第二個事件附帶的參數(shù))
this.$emit('childNotify', params)
}
}
}
</script>
參考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.html
希望本文所述對大家vue.js程序設計有所幫助。
相關文章
vue指令只能輸入正數(shù)并且只能輸入一個小數(shù)點的方法
這篇文章主要介紹了vue指令只能輸入正數(shù)并且只能輸入一個小數(shù)點的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
jdk1.8+vue elementui實現(xiàn)多級菜單功能
這篇文章主要介紹了jdk1.8+vue elementui實現(xiàn)多級菜單功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
解決elementui上傳組件el-upload無法第二次上傳問題
這篇文章主要介紹了解決elementui上傳組件el-upload無法第二次上傳問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
實例詳解vue.js淺度監(jiān)聽和深度監(jiān)聽及watch用法
這篇文章主要介紹了vue.js淺度監(jiān)聽和深度監(jiān)聽及watch用法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧2018-08-08
基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn)
這篇文章主要介紹了基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12

