您的位置:首页 > Web前端 > Vue.js

vue 中 父子组件传值 子父组件传值 非父子组件传值

2018-06-20 11:50 891 查看

父组件向子组件传值:

· 子组件在props中创建一个属性,用以接收父组件传过来的值

· 父组件中注册子组件

· 在子组件标签中添加子组件props中创建的属性

· 把需要传给子组件的值赋给该属性


父组件内容:

<template> <div>      我是父组件
{{msg}}        <!--子组件-->
<child :msg="value"></child> </div></template>
<script> import child from './child.vue'; export default{ data(){ return{ msg:'父组件', value:'我是父组件传来的'//传向子组件的值 } }, components:{ child } }</script>


子组件内容:

<template> <div class="child"> 我是子组件 {{msg}} </div></template>

<script> export default{ props:['msg'],//接收父组件传来的值 }</script>



子组件向父组件传值:

子组件内容:

在子组件中创建一个按钮,给按钮绑定一个点击事件


<template>   <div class="child"> 我是子组件 <button @click="put">点击向父组件传值</button> </div></template><script> export default{ methods:{ put(){ this.$emit('get','子组件传来的值')//在相应点击事件的函数中使用$emit来触发一个自定义事件,并传递一个参数 } } }</script>

父组件内容:

在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法

<template> <div> {{fromChild}} <child @get="show"></child> </div></template>

<script> import child from './child.vue'; export default{ data(){ return{ fromChild:'', } }, components:{ child, }, methods:{ show(e){ this.fromChild=e //接收子组件传来的值 } } }</script>



非父子组件传值:

非父子组件中两个组件没有联系,不能使用this来传值,所以我们只能通过第三方的变量,来达到传值的效果,这个第三方变量就是:bus

必须要有公共的实例(可以是空的),才能使用 

$emit
 获取 
$on
 的数据参数,实现组件通信

1.首先定义一个空的vue作为公共事件总线

(创建一个公共的js 例如:bus.js)

import Vue from 'vue';
let bus = new Vue();
export default bus;

2.创建两个不相关的组件,one.vue、two.vue

3.在one.vue中触发事件,

<template> <div> 我是组件1 <button @click="send">点击向组件2传值</button> </div></template>
<script>import bus from './bus.js' export default{ methods:{ send(){ bus.$emit('get','组件1传来的值') } } }</script>

在组件 two.vue 创建的钩子中监听事件

<template> <div> 我是组件2       {{value}} </div></template>

<script>import bus from './bus.js'; export default{ data(){ return{ value:'' } }, created(){ bus.$on('get',(e)=>{ this.value=e //接收one.vue中传来的值 }) } }</script>



阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: