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 路由子組件created和mounted不起作用的解決方法
今天小編就為大家分享一篇vue 路由子組件created和mounted不起作用的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue 添加和編輯用同一個表單,el-form表單提交后清空表單數(shù)據(jù)操作
這篇文章主要介紹了vue 添加和編輯用同一個表單,el-form表單提交后清空表單數(shù)據(jù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
el-table點擊某一行高亮并顯示小圓點的實現(xiàn)代碼
這篇文章主要介紹了el-table點擊某一行高亮并顯示小圓點,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
Vue3利用自定義指令進行內(nèi)容控制的實現(xiàn)方法
Vue3作為一個漸進式JavaScript框架,提供了強大的自定義指令功能,使得權限控制變得既簡單又高效,本文將詳細介紹如何在Vue3中使用自定義指令來判斷內(nèi)容是否顯示,以滿足不同用戶權限下的界面展示需求,需要的朋友可以參考下2024-04-04

