【问题标题】:Watch a prop change from parent to child观看从父母到孩子的道具变化
【发布时间】:2021-09-30 14:50:49
【问题描述】:

我试图在以下解决方案中实现观察者: How to listen for 'props' changes

我有一个名为“selectedItem”的属性,我试图将其传递给一个孩子并监视出现的值,以便我可以通过处理程序对其进行一些操作,但手表没有被触发出于某种原因。

这里是父子代码:

父(产品组件):

<template>
  <div class="container">
    <Popup item="selectedItem" />

    <b-table striped hover :items="products" :fields="fields">
      <template #cell(Edit)="data">
        <b-button
          v-b-modal="'edit-modal'"
          v-on:click="setSelectedItem(data.item)"
          variant="warning"
        >
          Edit
        </b-button>
      </template>
    </b-table>
  </div>
</template>

<script>
import Popup from "./Popup";

export default {
  name: "Products",
  components: { Popup },
  data() {
    return {
      products: [],
      countries: [],
      fields: [],
      selectedItem: null,
    };
  },
  methods: {
    getProducts() {
      fetch("http://localhost:5000/", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      })
        .then(async (res) => {
          try {
            let data = await res.json();
            this.products = data.products;
            this.countries = data.countries;
            this.fields = Object.keys(this.products[0]);
            this.fields.push({ key: "Edit", label: "Click & Edit" });
            console.log(this.fields);
          } catch (error) {
            console.log(error);
          }
        })
        .catch((error) => console.log(error));
    },
    setSelectedItem(item) {
      this.selectedItem = item;
    },
  },
  watch: {
    selectedItem: {
      handler(val) {
        console.log(val);
      },
      deep: true,
    },
  },
  created() {
    this.getProducts();
  },
};
</script>

子(弹出组件)

<template>
  <b-modal id="edit-modal">
    <!-- <b-button v-on:click="updateItem">update</b-button> -->
  </b-modal>
</template>

<script>
export default {
  name: "Popup",
  props: {
    selectedItem: Object,
  },
  data() {
    return {
      item: undefined
    };
  },
  watch: {
    selectedItem: {
      handler(val) {
        console.log(val);
      },
      deep: true,
    },
  },
};
</script>

我知道我在这里问了一个很多问题,但没有弄清楚我做错了什么。

【问题讨论】:

  • &lt;Popup item="selectedItem" /&gt; - 你真的在用这个还是一个错字?

标签: vue.js


【解决方案1】:

您的Popup 组件声明它接收名为selectedItem 的道具。但是您正在使用像&lt;Popup item="selectedItem" /&gt; 这样的弹出窗口,这意味着您将trying to pass a string "selectedItem" 放入一个名为item 的道具中

这就是你想要的:

<Popup :selectedItem="selectedItem" />

【讨论】:

  • 谢谢朋友。我忘记了字符串模板,也没有意识到我为道具使用了不同的名称。傻我。
猜你喜欢
  • 1970-01-01
  • 2019-11-24
  • 2017-08-26
  • 2022-12-16
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多