【问题标题】:Pass a method from parent to listener in childcomponent in vue将方法从父级传递给vue中子组件中的侦听器
【发布时间】:2020-09-28 20:17:32
【问题描述】:

我的父组件 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>

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

但是,如果我不想显示该值怎么办。只是将道具用作数据?

【问题讨论】:

    标签: javascript vue.js components


    【解决方案1】:

    你实际上并不需要观察者。 props 是响应式的,如果你只是在子组件的模板中引用{{ myProp }},它会在按钮被点击时重新渲染。

    【讨论】:

    • 谢谢!当然。 :) 如果我想在另一个函数中使用道具:this.myProp,如上面更新的示例所示?但是,如果我不想显示该值怎么办。只是将道具用作数据?
    • 任何引用 prop 的方法(通过this. MyProp)都可以访问当前值,即使它已更改。如果 prop 发生变化,任何引用 prop 的计算属性都将自动重新运行。
    猜你喜欢
    • 2017-06-24
    • 2021-06-29
    • 2017-01-07
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多