vue组件之间的通信
14
前言
作为一个vue初学者不得不了解的就是组件间的数据通信(暂且不谈vuex)。通信方式根据组件之间的关系有不同之处。组件关系有下面三种:父-->子、子-->父、非父子
父-->子
父向子传递数据通过props
**父组件代码**
<template>
<header-box>
import Header from './header'
export default {
name: 'index',
components: {
'header-box': Header
},
data () {
return {
showTitleTxt: '首页'
}
}
}
**子组件代码**
<template>
<header>
{{thisTitleTxt}}
export default {
name: 'header-box',
props: {
titleTxt: String
},
data () {
return {
thisTitleTxt: this.titleTxt
}
}
}
子-->父
子组件向父组件传递分为两种类型。
1、子组件改变父组件传递的props(你会发现通过props中的Object类型参数传输数据,可以通过子组件改变数据内容。这种方式是可行的,但是不推荐使用,因为官方定义prop是单向绑定)
2、通过$on和$emit
*通过props实现传递*
**父组件代码**
<template>
<header-box>
import Header from './header'
export default {
name: 'index',
components: {
'header-box': Header
},
data () {
return {
showTitleTxt: {
name: '首页'
}
}
}
}
**子组件代码**
<template>
<header>
{{thisTitleTxt.name}}
export default {
name: 'header-box',
props: {
titleTxt: Object
},
data () {
return {
thisTitleTxt: this.titleTxt.name
}
},
metheds: {
changeTitleTxt () {
this.titleTxt.name = '切换'
}
}
}
*通过$on,$emit*
**父组件代码**
<template>
{{ total }}
<button-counter>
**子组件代码**
<template>
<button>{{counter}}/<button>
export default {
name: 'button-counter',
data () {
return {
counter: 0
}
},
metheds: {
incrementCounter () {
this.$emit('increment')
this.counter++
}
}
}
非父子
简单情况下我们可以通过使用一个空的Vue实例作为中央事件总线
**main.js**
let bus = new Vue()
Vue.prototype.bus = bus
**header组件**
<template>
<header>{{title}}/<header>
**footer组件**
<template>
<footer>{{txt}}/<footer>
閱讀更多 紛亂的雨季 的文章