vue中this.$parent.attribute为undefined问题

vue中this.$parent.attribute为undefined问题
vue2.9.6

<template>
<el-container>
  <h1>{{say}}</h1><br>
  <button @click='changeChild'>changeChild</button>
  <child-component ref="child"></child-component>
</el-container>
</template>

<script>
export default {
  data () {
    return {
      say: "I'm parent."
    }
  },
  methods: {
    changeChild () {
    
      //这里父组件掉子组件没问题,改值后界面上立刻响应。
      this.$refs.child.say = new Date().getTime()
    }
  },
  components: {
    'child-component': {
      data () { return { say: "I'm child." } },
      template: "<div><h1>{{say}}</h1><button @click='changeParent'>changeParent</button></div>",
      methods: {
        changeParent () {
        
          //此处总是undefined,导致我无法动态的改say的值。
          console.info(this.$parent.say)
        }
      }
    }
  }
}
</script>

我在子组件中调用this.$parent.say总是undefined,我打印出$parent,里面没有say这个属性,非常奇怪。
我在网上看到的用法都是这样用,为何别人的就没问题呢。是我缺少什么配置吗?还是我用法有问题?
求解,谢谢!

阅读 7.9k
3 个回答

谢谢你们!我发现this.$parent并非意识里的parent,我用了2个$parent就可以了。
this.$parent.$parent.say。

this.$nextTick(()=>{
  console.info(this.$parent.say)
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题