vuejs component communication

When the application is complex, it is recommended to use vuex recommended by the vue official website. The following discusses the value transfer between components in a simple SPA (single-page application referred to as SPA).

First, the routing value

  The routing object is shown in the following figure:

  

  When jumping the page, the operation in the js code is as follows, using the <router-link> tag in the tag

1
2
3
4
5
6
this.$router.push({
                        name: 'routePage',
                        query/params: {
                            routeParams: params
                        }
 It should be noted that when using params to pass values, when the page is refreshed, the parameters will disappear, but using query will not have this problem.

 This is very convenient to use, but the url will become very long, and the interface cannot be used if it is not used for routing. The values ​​are as follows: this.$route.params.paramName and this.$route.query.paramName

   Note: Use params to pass the value, you can also refresh the page, the parameters are not lost, set this when naming the route:

[javascript] view plain copy
{  
      path: '/OrderDetail/:orderId/:type',  
      name: 'OrderDetail',  
      component: OrderDetail,  
      meta: {  
        title: 'Order Details',  
        needAuth: true  
      }  
}  
when using it:
[javascript] view plain copy
this.$router.push({name: 'OrderDetail', params: {orderId: id, type: 'buy'}})  
This way will navigate the route to the /OrderDetail/22aead11a99c4c91aa2169ac17d0ddb5/booking path
Reference: http://router.vuejs.org/zh-cn/essentials/named-routes.html

2. Call data and methods in components that use hierarchical relationships through $parent, $chlidren and other methods

  Called by the following method:

1
2
this.$parent.$data.id //Get the id in the parent element data
this.$children.$data.id //Get the id in the parent element data
  This is more flexible to use, but it is easy to cause code coupling too strong, resulting in difficult maintenance


1. The parent component passes the scene to the child component: an input box on the Father, which is passed to the Child component according to the input.

Parent component:

copy code
<template>
  <div>
    <input type="text" v-model="msg">
    <br>
    //Bind the child control property inputValue to the parent component msg property
    <child :inputValue="msg"></child>
  </div>
</template>
<style>

</style>
<script>
  export default{
    data(){
      return {
        msg: 'Please enter'
      }
    },
    components: {
      child: require('./Child.vue')
    }
  }
</script
copy code
Subassembly:

copy code
<template>
  <div>
    <p>{{inputValue}}</p>
  </div>
</template>
<style>

</style>
<script>
    export default{
        props: {
          inputValue: String
        }
    }
</script>
copy code
2. The sub-component passes values ​​to the parent component: the input box on the sub-component, the parent component listens when the input value changes, and a pop-up box pops up

 

 Parent component:

copy code
<template>
  <div>
//message is the notification bound on the child control; receiveMessage is the method after the parent component listens
    <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('Listen to child component changes'+text);
      }
    }
  }
</script>
copy code
Subassembly:

 

copy code
<template>
  <div>
    <input type="text" v-model="msg" @change="onInput">
  </div>
</template>
<script>
  export default{
    data(){
      return {
        msg: 'Please enter a value'
      }
    },
    methods: {
      onInput: function () {
        if (this.msg.trim()) {
          this.$emit('message', this.msg);
        }
      }
    }
  }
</script>

There is also a way for child components to use parent component data: prop

Prop
If the child component wants to use the data of the parent component, we need to get the data passed by the parent component through the props option of the child component. Below I use the format in the .vue file to write the example.
How to pass data
Reference the child component child.vue in the parent component father.vue, and pass the value of name to the child component.
?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<template>

  <div class="app">

    // message is defined in the child component's props

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

  </div>

</template>

<script>

  import child from './child.vue';

  export default
{

    components: {

      child

    },

    data() {

      return
{

        name: 'linxin'

      }

    }

  }

</script>
Declare the data it expects in the props option in the child component child.vue
?

1

2

3

4

5

6

7

8

9

<template>

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

</template>

<script>

  export default
{

    // Declare in props to get the data of the parent component and pass it through message

    props: ['message']

  }

</script>
Then the page will render: Hello linxin
Unidirectional data flow
When the name of the parent component changes, the child component will automatically update the view. But in child components, we don't modify props. If you must modify this data, you can use the following methods:
Method 1: Assign prop to a local variable, and then modify the local variable if you need to modify it without affecting prop
?

1

2

3

4

5

6

7

8

9

export default
{

  data(){

    newMessage: null

  },

  props: ['message'],

  created(){

    this.newMessage = this.message;

  }

}
Method 2: Process props in computed properties
?

1

2

3

4

5

6

7

8

export default
{

  props: ['message'],

  computed{

    newMessage(){

      return
this.newMessage + 'hahaha';

    }

  }

}
 


3. Pass data through eventBus (custom event)

  An eventBus can be defined globally before use

1
window.eventBus = new Vue();
  In the component that needs to pass parameters, define an emit to send the value that needs to be passed, and the key name can be defined by yourself (it can be an object)

1
eventBus.$emit('eventBusName', id);
  In the component that needs to accept parameters, use on to accept the value (or object)

1
//val is the passed value
eventBus.$on('eventBusName', function(val) {
 console.log(val)
})
  Finally remember to close this eventBus in beforeDestroy()

1
eventBus.$off('eventBusName');
Fourth, store data through localStorage or sessionStorage (Reference: http://blog.csdn.net/qq_32786873/article/details/70853819)
setItem stores value
Purpose: store value in key field
Usage: .setItem(key, value)
Code example:
sessionStorage.setItem("key", "value"); localStorage.setItem("site", "js8.in");


getItem gets value
Purpose: Get the value stored locally for the specified key
Usage: .getItem(key)
Code example:
var value = sessionStorage.getItem("key"); var site = localStorage.getItem("site");
Link: http://www.cnblogs.com/ygtq-island/p/6728137.html

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324959163&siteId=291194637