vue学习(一):组件通信
2018-06-24 00:05:10来源:未知 阅读 ()
# 父子组件之间的通信(props down, events up)
1、父组件向子组件传递(props down )
app.vue(父组件)
<template>
<div id="app">
<hello :text="msg"></hello>
</div>
</template>
<script>
import hello from '@/components/hello'
export default {
name: 'app',
data (){
return {
msg: "I come from parent"
}
},
components:{
hello
},
}
</script>
hello.vue(子组件)
<template>
<div class="hello">
<button type="button">{{ text }}</button>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: "I come from child"
}
},
props:[ 'text' ]
}
</script>
如图所示,按钮显示的信息来自父组件:

2、子组件向父组件传递(events up)
子组件通过this.$emit("事件名",参数)触发自定义事件
app.vue(父组件):
<template>
<div id="app">
<p>来自子组件的内容:<span>{{ msg}}</span></p>
<hello @get-msg-from-child="getMsg"></hello>
</div>
</template>
<script>
import hello from '@/components/hello'
export default {
name: 'app',
data (){
return {
msg: ""
}
},
components:{
hello
},
methods: {
getMsg (a){
this.msg = a;
}
}
}
</script>
hello.vue(子组件):
<template>
<div class="hello">
<button type="button" @click="showMsg">点我</button>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: "I come from child"
}
},
methods: {
showMsg (){
this.$emit('get-msg-from-child',this.msg)
}
}
}
</script>
点击“点我按钮”,会显示获取到的子组件的内容:

# 非父子组件通信
在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线; 在复杂的情况下,我们应该考虑使用专门的状态管理模式.(这里不涉及)。
bus.js:
import Vue from 'vue' var bus = new Vue(); export { bus }
app.vue(含有aaa和bbb组件):
<template>
<div id="app">
<aaa></aaa>
<bbb></bbb>
</div>
</template>
<script>
import aaa from '@/components/aaa'
import bbb from '@/components/bbb'
export default {
name: 'app',
components:{
aaa,
bbb
}
}
</script>
aaa.vue:
<template> <div class="a"> aaa的输入框: <input v-model="msg" @keyup="changeMsg"> </div> </template> <script> // 引入bus import {bus} from './bus.js' export default { data () { return { msg: "" } }, methods: { changeMsg (){ // 触发事件 bus.$emit("get-aaa-msg", this.msg) } } } </script>
bbb.vue:
<template>
<div class="b">
<p>bbb的内容:<span>{{msg}}</span></p>
</div>
</template>
<script>
import {bus} from './bus.js'
export default {
data () {
return {
msg: ""
}
},
mounted (){
// 自定义事件
bus.$on("get-aaa-msg", (msg) => {
this.msg = msg
})
}
}
</script>
显示结果如下:

当在aaa中输入内容,会在下面显示出来获取到的数据,如下:

标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- 如何用javascript连接access数据库 2020-03-20
- vue.js开发环境搭建教程 2020-03-16
- 在JavaScript中尽可能使用局部变量的原因 2020-03-08
- Vue input控件通过value绑定动态属性及修饰符的方法 2020-03-05
- 详解Webstorm 新建.vue文件支持高亮vue语法和es6语法 2020-02-07
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
