欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解vue2父组件传递props异步数据到子组件的问题

程序员文章站 2023-09-08 22:29:47
测试环境:vue v2.3.3, vue v2.3.1 案例一 父组件parent.vue // asyncdata为异步获取的数据,想传递给子组件使...

测试环境:vue v2.3.3, vue v2.3.1

案例一

父组件parent.vue

// asyncdata为异步获取的数据,想传递给子组件使用
<template>
 <div>
  父组件
  <child :child-data="asyncdata"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncdata: ''
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncdata = 'async data'
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

子组件child.vue

<template>
 <div>
  子组件{{childdata}}
 </div>
</template>

<script>
 export default {
  props: ['childdata'],
  data: () => ({
  }),
  created () {
   console.log(this.childdata) // 空值
  },
  methods: {
  }
 }
</script>

上面按照这里的解析,子组件的html中的{{childdata}}的值会随着父组件的值而改变,但是created里面的却不会发生改变(生命周期问题)

案例二

parent.vue

<template>
 <div>
  父组件
  <child :child-object="asyncobject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncobject: ''
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncobject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件<!--这里很常见的一个问题,就是{{childobject}}可以获取且没有报错,但是{{childobject.items[0]}}不行,往往有个疑问为什么前面获取到值,后面获取不到呢?-->
  <p>{{childobject.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
  }),
  created () {
   console.log(this.childobject) // 空值
  },
  methods: {
  }
 }
</script>

created里面的却不会发生改变, 子组件的html中的{{{childobject.items[0]}}的值虽然会随着父组件的值而改变,但是过程中会报错

// 首先传过来的是空,然后在异步刷新值,也开始时候childobject.items[0]等同于''.item[0]这样的操作,所以就会报下面的错
vue.esm.js?8910:434 [vue warn]: error in render function: "typeerror: cannot read property '0' of undefined"

针对二的解决方法:

使用v-if可以解决报错问题,和created为空问题

// parent.vue
<template>
 <div>
  父组件
  <child :child-object="asyncobject" v-if="flag"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncobject: '',
   flag: false
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncobject = {'items': [1, 2, 3]}
    this.flag = true
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件
  <!--不报错-->
  <p>{{childobject.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
  }),
  created () {
   console.log(this.childobject)// object {items: [1,2,3]}
  },
  methods: {
  }
 }
</script>

子组件使用watch来监听父组件改变的prop,使用methods来代替created

parent.vue

<template>
 <div>
  父组件
  <child :child-object="asyncobject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncobject: ''
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncobject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件<!--1-->
  <p>{{test}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
   test: ''
  }),
  watch: {
   'childobject.items': function (n, o) {
    this.test = n[0]
    this.updata()
   }
  },
  methods: {
   updata () { // 既然created只会执行一次,但是又想监听改变的值做其他事情的话,只能搬到这里咯
    console.log(this.test)// 1
   }
  }
 }
</script>

子组件watch computed data 相结合,有点麻烦

parent.vue

<template>
 <div>
  父组件
  <child :child-object="asyncobject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncobject: undefined
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncobject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件<!--这里很常见的一个问题,就是{{childobject}}可以获取且没有报错,但是{{childobject.items[0]}}不行,往往有个疑问为什么前面获取到值,后面获取不到呢?-->
  <p>{{test}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
   test: ''
  }),
  watch: {
   'childobject.items': function (n, o) {
    this._test = n[0]
   }
  },
  computed: {
   _test: {
    set (value) {
     this.update()
     this.test = value
    },
    get () {
     return this.test
    }
   }
  },
  methods: {
   update () {
    console.log(this.childobject) // {items: [1,2,3]}
   }
  }
 }
</script>

使用emit,on,bus相结合

parent.vue

<template>
 <div>
  父组件
  <child></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
  }),
  components: {
   child
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    // 触发子组件,并且传递数据过去
    this.$bus.emit('triggerchild', {'items': [1, 2, 3]})
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件
  <p>{{test}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
   test: ''
  }),
  created () {
   // 绑定
   this.$bus.on('triggerchild', (parmas) => {
    this.test = parmas.items[0] // 1
    this.updata()
   })
  },
  methods: {
   updata () {
    console.log(this.test) // 1
   }
  }
 }
</script>

这里使用了这个库,parent.vue和child.vue必须公用一个事件总线(也就是要引入同一个js,这个js定义了一个类似let bus = new vue()的东西供这两个组件连接),才能相互触发

使用prop default来解决{{childobject.items[0]}}

parent.vue

<template>
 <div>
  父组件
  <child :child-object="asyncobject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncobject: undefined // 这里使用null反而报0的错
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // settimeout模拟异步数据
   settimeout(() => {
    this.asyncobject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子组件<!--1-->
  <p>{{childobject.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  props: {
   childobject: {
    type: object,
    default () {
     return {
      items: ''
     }
    }
   }
  },
  data: () => ({
  }),
  created () {
   console.log(this.childobject) // {item: ''}
  }
 }
</script>

在说用vuex解决方法的时候,首先看看案例三

案例三

main.js

import vue from 'vue'
import app from './app'
import router from './router'
import vuebus from 'vue-bus'
import index from './index.js'
vue.use(vuebus)

vue.config.productiontip = false
import vuex from 'vuex'
vue.use(vuex)
const store = new vuex.store({
 modules: {
  index
 }
})
/* eslint-disable no-new */
new vue({
 el: '#app',
 store,
 router,
 template: '<app/>',
 components: { app }
})

index.js

const state = {
 asyncdata: ''
}

const actions = {
 asyncaction ({ commit }) {
  settimeout(() => {
   commit('asyncmutation')
  }, 2000)
 }
}
const getters = {
}

const mutations = {
 asyncmutation (state) {
  state.asyncdata = {'items': [1, 2, 3]}
 }
}

export default {
 state,
 actions,
 getters,
 mutations
}

parent.vue

<template>
 <div>
  父组件
  <child></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
  }),
  components: {
   child
  },
  created () {
   this.$store.dispatch('asyncaction')
  },
  mounted () {
  }
 }
</script>

child.vue

<template>
 <div>
  子组件
  <p>{{$store.state.index.asyncdata.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  data: () => ({
  }),
  created () {
  },
  methods: {
  }
 }
</script>

{{$store.state.index.asyncdata.items[0]}}可以取到改变的值,但是过程中还是出现这样的报错,原因同上

复制代码 代码如下:

[vue warn]: error in render function: "typeerror: cannot read property '0' of undefined"

所以这里的解决方法是:vuex结合computed、mapstate或者合computed、mapgetters

parent.vue

<template>
 <div>
  父组件
  <child></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
  }),
  components: {
   child
  },
  created () {
   this.$store.dispatch('asyncaction')
  },
  mounted () {
  }
 }
</script>

child.vue

<template>
 <div>
  子组件
  <p>{{item0}}</p>
  <p>{{item}}</p>
 </div>
</template>

<script>
 import { mapstate, mapgetters } from 'vuex'
 export default {
  data: () => ({
   test: ''
  }),
  computed: {
   ...mapgetters({
    item: 'getasyncdata'
   }),
   ...mapstate({
    item0: state => state.index.asyncdata
   })
  },
  created () {
  },
  methods: {
  }
 }
</script>

index.js

const state = {
 asyncdata: ''
}

const actions = {
 asyncaction ({ commit }) {
  settimeout(() => {
   commit('asyncmutation', {'items': [1, 2, 3]})// 作为参数,去调用mutations中的asyncmutation方法来对state改变
  }, 2000)
 }
}
const getters = {
 getasyncdata: state => state.asyncdata
}

const mutations = {
 asyncmutation (state, params) {
  state.asyncdata = params.items[0] // 此时params={'items': [1, 2, 3]}被传过来赋值给asyncdata,来同步更新asyncdata的值,这样html就可以拿到asyncdata.items[0]这样的值了
 }
}

export default {
 state,
 actions,
 getters,
 mutations
}

注意上面的

....
commit('asyncmutation', {'items': [1, 2, 3]})
...
state.asyncdata = params.items[0]

如果写成这样的话

commit('asyncmutation')
state.asyncdata = {'items': [1, 2, 3]}

首先asyncaction是个异步的操作,所以asyncdata默认值为空,那么还是导致,child.vue这里报0的错

<template>
 <div>
  子组件
  <p>{{item0}}</p>
  <p>{{item}}</p>
 </div>
</template>

不过根据以上的案例,得出来一个问题就是异步更新值的问题,就是说开始的时候有个默认值,这个默认值会被异步数据改变,比如说这个异步数据返回的object,如果你用props的方式去传递这个数据,其实第一次传递的空值,第二次传递的是更新后的值,所以就出现{{childobject.items[0]}}类似这种取不到值的问题,既然说第一次是空值,它会这样处理''.items[0],那么我们是不是可以在html判断这个是不是空(或者在computed来判断是否为默认值),所以把案例二的child.vue

<template>
 <div>
  <p>{{childobject != '' ? childobject.items[0]: ''}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childobject'],
  data: () => ({
  }),
  created () {
   console.log(this.childobject) // 空值
  },
  methods: {
  }
 }
</script>

这样是可以通过不报错的,就是created是空值,猜想上面vuex去stroe也可以也可以这样做

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。