vuejs 组件通讯

在应用复杂时,推荐使用vue官网推荐的vuex,以下讨论简单SPA(single-page application 简称为 SPA)中的组件间传值。

一、路由传值

  路由对象如下图所示:

  

  在跳转页面的时候,在js代码中的操作如下,在标签中使用<router-link>标签

1
2
3
4
5
6
this.$router.push({
                        name: 'routePage',
                        query/params: {
                            routeParams: params
                        }
 需要注意的是,实用params去传值的时候,在页面刷新时,参数会消失,用query则不会有这个问题。

 这样使用起来很方便,但url会变得很长,而且如果不是使用路由跳转的界面无法使用。取值方式分别为:this.$route.params.paramName和this.$route.query.paramName

   注:使用params传值,也可以做到页面刷新,参数不丢失,在命名路由时这样设置:

[javascript] view plain copy
{  
      path: '/OrderDetail/:orderId/:type',  
      name: 'OrderDetail',  
      component: OrderDetail,  
      meta: {  
        title: '订单详情',  
        needAuth: true  
      }  
}  
使用时:
[javascript] view plain copy
this.$router.push({name: 'OrderDetail', params: {orderId: id, type: 'buy'}})  
这种方式会把路由导航到 /OrderDetail/22aead11a99c4c91aa2169ac17d0ddb5/booking 路径
参考:http://router.vuejs.org/zh-cn/essentials/named-routes.html

二、通过$parent,$chlidren等方法调取用层级关系的组件内的数据和方法

  通过下面的方法调用:

1
2
this.$parent.$data.id  //获取父元素data中的id
this.$children.$data.id  //获取父元素data中的id
  这样用起来比较灵活,但是容易造成代码耦合性太强,导致维护困难


1,父组件向子组件传递场景:Father上一个输入框,根据输入传递到Child组件上。

父组件:

复制代码
<template>
  <div>
    <input type="text" v-model="msg">
    <br>
    //将子控件属性inputValue与父组件msg属性绑定
    <child :inputValue="msg"></child>
  </div>
</template>
<style>

</style>
<script>
  export default{
    data(){
      return {
        msg: '请输入'
      }
    },
    components: {
      child: require('./Child.vue')
    }
  }
</script
复制代码
子组件:

复制代码
<template>
  <div>
    <p>{{inputValue}}</p>
  </div>
</template>
<style>

</style>
<script>
    export default{
        props: {
          inputValue: String
        }
    }
</script>
复制代码
2,子组件向父组件传值场景:子组件上输入框,输入值改变后父组件监听到,弹出弹框

 

 父组件:

复制代码
<template>
  <div>
//message为子控件上绑定的通知;recieveMessage为父组件监听到后的方法
    <child2 v-on:message="recieveMessage"></child2>
  </div>
</template>
<script>
  import {Toast} from 'mint-ui'
  export default{
    components: {
      child2: require('./Child2.vue'),
      Toast
    },
    methods: {
      recieveMessage: function (text) {
        Toast('监听到子组件变化'+text);
      }
    }
  }
</script>
复制代码
子组件:

 

复制代码
<template>
  <div>
    <input type="text" v-model="msg" @change="onInput">
  </div>
</template>
<script>
  export default{
    data(){
      return {
        msg: '请输入值'
      }
    },
    methods: {
      onInput: function () {
        if (this.msg.trim()) {
          this.$emit('message', this.msg);
        }
      }
    }
  }
</script>

还有一个子组件使用父组件数据的方法:prop

Prop
子组件想要使用父组件的数据,我们需要通过子组件的 props 选项来获得父组件传过来的数据。以下我使用在 .vue 文件中的格式来写例子。
如何传递数据
在父组件 father.vue 中引用子组件 child.vue,把 name 的值传给 child 组件。
?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<template>

  <div class="app">

    // message 定义在子组件的 props 中

    <child :message="name"></child>

  </div>

</template>

<script>

  import child from './child.vue';

  export default
{

    components: {

      child

    },

    data() {

      return
{

        name: 'linxin'

      }

    }

  }

</script>
在子组件 child.vue 中的 props 选项中声明它期待获得的数据
?

1

2

3

4

5

6

7

8

9

<template>

  <span>Hello {{message}}</span>

</template>

<script>

  export default
{

    // 在 props 中声明获取父组件的数据通过 message 传过来

    props: ['message']

  }

</script>
那么页面中就会渲染出:Hello linxin
单向数据流
当父组件的 name 发生改变,子组件也会自动地更新视图。但是在子组件中,我们不要去修改 prop。如果你必须要修改到这些数据,你可以使用以下方法:
方法一:把 prop 赋值给一个局部变量,然后需要修改的话就修改这个局部变量,而不影响 prop
?

1

2

3

4

5

6

7

8

9

export default
{

  data(){

    newMessage: null

  },

  props: ['message'],

  created(){

    this.newMessage = this.message;

  }

}
方法二:在计算属性中对 prop 进行处理
?

1

2

3

4

5

6

7

8

export default
{

  props: ['message'],

  computed{

    newMessage(){

      return
this.newMessage + ' 哈哈哈';

    }

  }

}
 


三、通过eventBus传递数据(自定义事件)

  使用前可以在全局定义一个eventBus

1
window.eventBus = new Vue();
  在需要传递参数的组件中,定义一个emit发送需要传递的值,键名可以自己定义(可以为对象)

1
eventBus.$emit('eventBusName', id);
  在需要接受参数的组件重,用on接受该值(或对象)

1
//val即为传递过来的值
eventBus.$on('eventBusName', function(val) {
 console.log(val)
})
  最后记住要在beforeDestroy()中关闭这个eventBus

1
eventBus.$off('eventBusName');
四、通过localStorage或者sessionStorage来存储数据(参考:http://blog.csdn.net/qq_32786873/article/details/70853819)
setItem存储value
用途:将value存储到key字段
用法:.setItem( key, value)
代码示例:
sessionStorage.setItem("key", "value"); localStorage.setItem("site", "js8.in");


getItem获取value
用途:获取指定key本地存储的值
用法:.getItem(key)
代码示例:
var value = sessionStorage.getItem("key"); var site = localStorage.getItem("site");
链接:http://www.cnblogs.com/ygtq-island/p/6728137.html

  

原文地址:https://www.cnblogs.com/lgjc/p/8950374.html