【问题标题】:Vue: Set child-component data with props values not workingVue:使用道具值设置子组件数据不起作用
【发布时间】:2017-12-28 17:47:27
【问题描述】:

简单地说,我有两个组件:

  • 父组件,它传递一个名为“profile”的 prop 对象
  • 子组件接收配置文件属性

配置文件值是这样的对象:

{
  name: "Something",
  email: "some@thing.com"
}

会发生什么?

子组件完美接收模板中的配置文件值,但似乎无法检索并将其设置为组件数据。

目标是什么?

我想用配置文件电子邮件属性初始化值“电子邮件”。

我期待什么?

export default {
  props: ["profile"],
  data() {
    return {
      email: this.profile.email
    }
  }
}

更新

我没有指定电子邮件是用作模型的数据值。 我刚刚尝试删除它并简单地在模板中打印电子邮件的值,它也不起作用。

<!-- PARENT COMPONENT -->

<template>
  <dialog-settings ref="dialogSettings" :profile="profile"></dialog-settings>
</template>

<script>

import Auth from "../services/apis/auth";
import DialogSettings from "../components/dialog-settings";

export default {
	name: "app",
  components: {
    "dialog-settings": DialogSettings
  },
  beforeCreate() {
    Auth.checkToken()
      .then(profile => {
        this.profile = profile;
      })
      .catch(err => {
      });
  },
  data() {
    return {
      title: "App",
      drawer: true,
      profile: {},
      navItems: []
    };
  }
}
</script>

<!-- CHILD COMPONENT -->

<template>
  {{profile}} <!-- All the fields are passed and available (e.g. profile.email)-->
  {{email}} <!-- Email is not defined -->
</template>

<script>

import Auth from "../services/apis/auth";
import DialogSettings from "../components/dialog-settings";

export default {
	name: "dialog-settings",
  props: ["profile"],
  data() {
    return {
      email: this.profile.email
    }
  }
}
</script>

更新 2

我已经尝试了几件事,我认为问题在于 beforeCreate() 中对 API 的异步调用。

【问题讨论】:

  • 这必须工作。我在您的代码中看不到任何错误。发布您的父子组件的完整代码。

标签: javascript vuejs2


【解决方案1】:

您的子组件电子邮件属性应该是一个计算值

<!-- CHILD COMPONENT -->

<template>
  <div>
    {{profile}} <!-- All the fields are passed and available (e.g. profile.email)-->
    {{email}} <!-- Email is not defined -->
  </div>
</template>

<script>

import Auth from "../services/apis/auth";
import DialogSettings from "../components/dialog-settings";

export default {
    name: "dialog-settings",
  props: ["profile"],
  data() {
    return {
    }
  },
  computed: {
    email () {
      return this.profile ? this.profile.email : 'no email yet'
    }
  }
}
</script>

这是因为父组件属性是在渲染子组件后设置的。 “数据”不是响应式的,它在创建组件时设置一次。 Prop 'profile" 是响应式的,因此首先在您渲染组件时您应该看到 {} 并且在设置了来自 Auth 的响应之后。 如果您仍想将其保留在数据中,则可以这样显示子组件:

<dialog-settings ref="dialogSettings" :profile="profile" v-if="profile.email"></dialog-settings>

但我不建议这样做!

【讨论】:

  • 由于您不推荐这种情况,您的最佳做法是什么?
  • 我建议您使用我帖子顶部的这个计算属性解决方案。我不建议只用 v-if 做这个。
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 2022-11-17
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多