vue子传父,一直报错

vue子传父,一直报错,我是把this.$emit('写在父级里的自定义事件名字',需要传递的数据),写在了子组件的生命周期created里面的,但是一直提示报错请看下面的报错截图,我搜了下说是需要传递的是字符串,但是我传递的是一个数组。我很肯定我传的确实是字符串,是在发请求拿到大对象里面在点的属性拿到的数据,为什么会提示我传递的是数组尼?我单独写了一个点击事件测试了下传递数据居然是可以成功传的,这是为什么?不支持写在created里面吗?不应该吧。

 <!-- 父组件 -->
<template>
  <div class="header">
    <van-search
      v-model="SearchValue"
      @search='EnterSearch'
  :placeholder="placeholderValue"
    >
    </van-search>
    <HistoryHot @myEvent="handleEvent"></HistoryHot>
  </div>
</template>
<script>
import HistoryHot from '@/components/HistoryHot';
export default {
 
  data() {
    return {
      SearchValue: "",
      placeholderValue: "",
    };
  },
   components:{
    HistoryHot
  },
  methods: {
  // 接受来自子组件的数据
    handleEvent(event){
      this.placeholderValue=event
      }
  },

};
</script>
 <!-- 子组件 -->
created(){
 <!-- 写在生命周期就会报错。也就是我文中所说的问题 -->
    this.$emit("myEvent",this.defaultKeyword)

  },
methods: {
gethome(){
 <!-- 这是我目前解决的办法 -->
 this.$emit("myEvent",this.defaultKeyword)
}
 
  },
阅读 2.8k
3 个回答

你的gethome方法里应该是先发送了ajax请求再调emit的吧,而且我猜你现在的emit其实是写在ajax请求的回调里的,比如

axios.gat('xxxx').then(res=>{
// 某些操作
thos.$emit('myEvent',this.defaultKeyword)
})

当你在写在生命周期里的时候

created(){
    this.gethome()
    // 上命那行执行完的时候,gethome里面发起的ajax请求其实还没有返回结果,defaultKeyword还是个默认值,但是我不知道你的默认值是什么 
    this.$emit("myEvent",this.defaultKeyword)

},

补充一下子组件的代码的执行顺序吧:

created(){
    console.log('执行顺序 1。这个时候 defaultKeyword=[],这是你设置的默认值')
    this.gethome()
    console.log('执行顺序 4。http请求还没响应,gethome就返回了。这个时候 defaultKeyword=[]')
    this.$emit("myEvent",this.defaultKeyword) // 这里传给父组件的值自然就是[]了
},
methods: {
    gethome(){
        console.log('执行顺序 2。这个时候 defaultKeyword=[]')
        axios.get('xxxxxx').then(res=>{
            console.log('执行顺序 5。http请求有结果了')
            this.defaultKeyword = res.data.xxxxxx
            // this.defaultKeyword 终于不再是[]了
            this.$emit("myEvent",this.defaultKeyword) // 这时传给父组件的才是正确值
        })
        console.log('执行顺序 3。上面的请求是异步的,这个http请求还没响应,代码就执行往下跑了。这个时候 defaultKeyword=[]')
    }
}

然后,如果你非要吧emit写在created里面的话,也不是不行:

created(){
    console.log('执行顺序 1。这个时候 defaultKeyword=[],这是你设置的默认值')
    this.gethome().then(()=>{
        console.log('执行顺序 5。')
        this.$emit("myEvent",this.defaultKeyword) // 这时传给父组件的是正确值
    })
    console.log('执行顺序 3。http请求还没响应,gethome就返回了。这个时候 defaultKeyword=[]')
},
methods: {
    gethome(){
        console.log('执行顺序 2。这个时候 defaultKeyword=[]')
        // 注意,下面的一定要return axios.get...
        return axios.get('xxxxxx').then(res=>{
            console.log('执行顺序 4。http请求有结果了')
            this.defaultKeyword = res.data.xxxxxx
            // this.defaultKeyword 终于不再是[]了
        })
    }
}

然后还有 async、await的写法我就不列举了。

楼上说的应该是对的。 子组件 defaultKeyword 的初始值是有问题的。

从提示来看是 :placeholder="placeholderValue" 这里传入的数据类型有问题。

问题得到解决,1就是异步导致。2在把初始化值类型改成字符串,上面也有人分析了一遍。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题