JavaScript - Data transfer between vue and components fails
phpcn_u1582
phpcn_u1582 2017-05-19 10:46:04
0
3
685

Event Bus is used for data transfer between the two components, but a problem occurred during data assignment.

Components that accept data:

<template>
  <p>
     <h1>{{movie.name}}</h1>
  </p>
</template>

<script>
  import Bus from '../bus.js'
  export default {
    name: 'MovieDetail',
    data: function () {
      return {
        movie: {},
        index: 110
      }
    },
    methods: {
      downloadPic () {
        console.log('name=' + this.movieName + ', name2=' + this.movie.name)
      }
    },
    created () {
      Bus.$on('loadMovie', (index, movie) => {
        console.log('index=' + this.index + ', movie=' + this.movie)
        this.setMovie(movie)
        this.setIndex(index)
        console.log('movie name=' + this.movie.name)
      })
    },
    computed: {
      movieName: function () {
        if (this.movie) {
          return this.movie.name
        }
      }
    }
  }
</script>

Console, you can see in the log that the created function has been called and this.movie has been reassigned, but the UI on the interface has not changed, and the current this.movie printed is still an empty object. Why is this?

phpcn_u1582
phpcn_u1582

reply all(3)
小葫芦

Answer it yourself, mainly because I don’t understand the mechanism of Bus. When that component created callback, the emit of another component had already been sent, resulting in on not receiving the event.

習慣沉默

When assigning an object in Vue, if its attributes are not declared in the data, dynamic assignment may not work. You can try adding a name attribute and it should be fine. You can check out the official instructions of vue https://vuefe.cn/v2/guide/rea... The first step to advance——change detection problem

Due to limitations of modern Javascript (and the deprecation of Object.observe), Vue cannot detect the addition or deletion of object properties. Since Vue performs the getter/setter conversion process on the property when initializing the instance, the property must exist on the data object in order for Vue to convert it so that it is responsive.

仅有的幸福

Post all the codes?

this.setMovie(movie)
this.setIndex(index)

I don’t know what these two did.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template