简体   繁体   English

在vue中将方法从父级传递给子组件中的侦听器

[英]Pass a method from parent to listener in childcomponent in vue

I have a button in my parent component App.vue and want to listen to buttonclick on my childcomponent and passing an incremental number every time the button is clicked.我的父组件 App.vue 中有一个按钮,我想在我的子组件上收听 buttonclick 并在每次单击该按钮时传递一个递增的数字。 At the moment I am passing the value as a prop and are watching for a change in my childcomponent with a watch: {目前,我正在将值作为道具传递,并正在用watch: {

This works fine.这很好用。 However, since I am pretty new to vue I wonder is there a better way or is this the recommended way of doing this?但是,由于我是 vue 的新手,我想知道是否有更好的方法或者这是推荐的方法吗?

App.vue App.vue

<template>
  <div id="app">
    <button @click="myMethod">To child</button>
    <Mycomponent :myProp="count" />
  </div>
</template>

<script>
import Mycomponent from "./components/Mycomponent";

export default {
  name: "App",
  components: {
    Mycomponent
  },

  data() {
    return {
      count: 0
    };
  },
  methods: {
    myMethod() {
      this.count++;
    }
  }
};
</script>

Mycomponent.vue我的组件.vue

<template>
  <div>
    {{myNumber}}
  </div>
</template>
<script>

export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },

  data() {
    return {
      myNumber: 0
    };
  },

  watch: {
    myProp: {
      deep: true,
      immediate: true,
      handler(newValue) {
        try {
          console.log("Print my value in the consule: ", newValue);
          this.myNumber = newValue
        } catch (err) {
          console.log("no data yet ...");
        }
      }
    }
  }
};
</script>

UPDATED EXAMPLE FOR REACHING PROP IN CHILD COMPONENT在子组件中获取道具的更新示例

<template>
  <div>
// what if I dont want to display myProp in the template? Just store the data
    {{myProp}} 
    <button @click="myMethod">Method</button>
  </div>
</template>
<script>
export default {
  name: "Mycomponent",
  props: {
    myProp: {
      type: Number
    }
  },
  methods: {
    myMethod() {
      console.log("print myProp ", this.myProp);
    }
  }
};
</script>

But what about if I don't want to display the value.但是,如果我不想显示该值怎么办。 Just use the prop as data?只是将道具用作数据?

You actually don't need the watcher.你实际上不需要观察者。 Props are reactive, and if you just reference {{ myProp }} in the child component's template, it will re-render whenever the button is clicked. Props 是反应式的,如果您只是在子组件的模板中引用{{ myProp }} ,它会在单击按钮时重新呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM