从父母到孩子的交付数据

时间:2018-04-22 14:18:09

标签: vue.js vuejs2

在谷歌上搜索几个小时并尝试所有国王示例后,我仍然无法弄清楚如何调用位于孩子中的函数或将任何数据传递给父母的子项。我尝试了很多没有成功的例子,我对Vue感到很困惑,将数据传递给孩子这么复杂吗?以下是我从其中一个示例中得出的结果,但它不能与我合作,也许我在这里做错了什么?谢谢:(

parent.vue

<template>
   export default {
         name:'parent'
         data:{
             retrun:{
                  dataTochild:''
             }
         },
         methods:{
             callToChild:function(){
                 this.dataTochild = 'Hello Child'
             }
         }
   }
</template>

<child :myprop="dataTochild" />
<input @click="this.callToChild" />

child.vue

<template>
export default {
   name:'child',
   props:['myprop'],
   watch:{ 
     myprop:function(){
      alert('Hello Parent')
     }
   }
}
<template>

顺便说一下,我正在使用Vue 2版本!

1 个答案:

答案 0 :(得分:1)

returnretrun)上有拼写错误,您遗漏的代码可能存在其他错误。

现场演示

此处正在处理live demo

代码

<template>
  <div class="parent">
    <child :myprop="dataTochild" />
    <button @click="callToChild">Press me!</button>
  </div>
</template>

<script>
import Child from "./Child.vue";

export default {
  name: "Parent",
  data() {
    return {
      dataTochild: "",
      counter: 0
    };
  },
  methods: {
    callToChild: function() {
      this.counter = this.counter + 1;
      this.dataTochild = "Hello Child " + this.counter;
    }
  },
  components: {
    Child
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
button {
  width: 200px;
  height: 60px;
}
</style>
儿童
<template>
  <div class="child">
    <p>{{ myprop }}</p>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: ["myprop"],
  watch: {
    myprop: function() {
      console.log("Hello Parent");
      alert("Hello Parent");
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
div.child {
  width: 400px;
  height: 100px;
  margin: auto;
}
</style>