// 非父子组件传值
// 1 引入vueEvent
// 2 VueEvent.$emit('to-news', this.msg) 广播组件
// 3 在news组件里接收
import Vue from 'vue'
const VueEvent = new Vue()
export default VueEvent
<template>
<div>Home
<button @click="getHomeData()">Home请求数据</button>
<ul>
<li v-for="(item,key) in list" :key=key>
{{item.title}}
</li>
</ul>
<!-- 给子组件传值绑定title属性 -->
<v-header :title='title' :run="run" :home="this" ref='header'></v-header>
<button @click="getSonData()">主动获取子组件的属性和方法</button>
<br>
<hr>
<!-- 非父子组件通讯 -->
<button @click="emitNews()">非父子组件传值----给news组件传值</button>
<hr>
<v-life v-if="flag"></v-life>
<button @click="flag=!flag">挂载和卸载组件</button>
</div>
</template>
<script>
// 父组件给子组件传值
// 1.父组件调用子组件的时候 绑定动态属性
// <v-header :title="title"></v-header>
// 2、在子组件里面通过 props接收父组件传过来的数据
// props:['title']
// props:{
// 'title': String}
// 3.直接在子组件里面使用
// 父组件主动获取子组件的数据和方法:
// 1.调用子组件的时候定义一个ref
// <v-header ref="header"></v-header>
// 2.在父组件里面通过
// this.$refs.header.属性
// this.$refs.header.方法
// 子组件主动获取父组件的数据和方法:
// this.$parent.数据
// this.$parent.方法
// 非父子组件传值
// 1 引入vueEvent
// 2 VueEvent.$emit('to-news', this.msg) 广播组件
// 3 在news组件里接收
import VueEvent from '../model/VueEvent.js'
import Header from './Header.vue'
import Life from './Life.vue'
import Axios from 'axios'
export default {
data () {
return {
msg: 'home',
flag: true,
list: [],
title: '父组件要传给子组件的值'
}
},
components: {
'v-header': Header,
'v-life': Life
},
methods: {
getHomeData () {
// 请求数据
var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
Axios.get(api).then((response) => {
this.list = response.data.result
}).catch((error) => {
console.log(error)
})
},
run (data) {
// 子组件通过执行run方法传递过来的值
console.log(data)
alert('我是父组件的run方法')
},
getSonData () {
alert(this.$refs.header.msg)
this.$refs.header.sonRun()
},
emitNews () {
// 广播组件
VueEvent.$emit('to-news', this.msg)
}
},
mounted () {
VueEvent.$on('to-home', (data) => {
console.log(data)
})
}
}
</script>
<style lang="css" scope>
</style>
<template>
<div>
<hr>
<h2>新闻组件-------非父子组件传值</h2>
<button @click="emitHome()">给home组件广播-非父子组件传值</button>
<hr>
</div>
</template>
<script>
import VueEvent from '../model/VueEvent.js'
export default {
data () {
return {
msg: '我是新闻组件'
}
},
methods: {
// 广播
emitHome () {
VueEvent.$emit('to-home', this.msg)
}
},
mounted () {
VueEvent.$on('to-news', (data) => {
console.log(data)
})
}
}
</script>
<style scoped>
</style>