簡體   English   中英

在vue中將方法從父級傳遞給子組件中的偵聽器

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

我的父組件 App.vue 中有一個按鈕,我想在我的子組件上收聽 buttonclick 並在每次單擊該按鈕時傳遞一個遞增的數字。 目前,我正在將值作為道具傳遞,並正在用watch: {

這很好用。 但是,由於我是 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>

我的組件.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>

在子組件中獲取道具的更新示例

<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>

但是,如果我不想顯示該值怎么辦。 只是將道具用作數據?

你實際上不需要觀察者。 Props 是反應式的,如果您只是在子組件的模板中引用{{ myProp }} ,它會在單擊按鈕時重新呈現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM