【问题标题】:What is a proper way to deal with Vue.js props that from the response of backend什么是处理来自后端响应的 Vue.js 道具的正确方法
【发布时间】:2017-07-27 13:38:01
【问题描述】:

我想知道如果道具来自后端的响应,那么在 Vue.js 中处理道具的正确方法是什么?

好的,假设子组件有一个名为prop 的person。 name 是个人对象。

    <template>
      {{ person.name }}
    <template>

    <script>
    export default {
        name: 'ChildComponent',
        props:['person'],
        created(){
           this.getName();
        },
        data(){return{name:''}},
        methods:{
          getName(){
             this.name = this.person.name;
          }
    }

    </script>

父组件是这样的

    <template>
      <ChildComponent :person="person"></ChildComponent>
    <template>

    <script>
    export default {
        name: 'ParentComponent',
        created(){
           this.getPerson();
        }
        data(){
          return {
             person: null
          }
        },
        methods:{getPerson(){
          // send request to server or api then update name 
          sendrequest().then(person => { this.person = person});
       }}
    </script>

首先,在得到响应之前,会有一个警告can't get name from person。 我知道两种处理方法:

  1. &lt;ChildComponent :person="person" v-if="person"&gt;&lt;/ChildComponent&gt;
  2. 注意person prop in,每次更改人员时,重新运行子组件中的 getName() 方法或将 name 设置为计算属性。

所以问题又来了,他们是处理这个问题的正确方法吗?还有其他一些方法,比如使用 Vuex 吗?

谢谢

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    这实际上取决于您的用例,如果您在准备好之前不想显示该人,那么v-if 似乎是正确的方法。

    如果你想在人物对象准备好之前显示一些东西,你有两个选择:

    1. 给人一个默认名称,或用空名称初始化它
    2. 在人员准备好之前显示加载组件

    【讨论】:

      【解决方案2】:

      这不是 vue 警告。基本上这是 javascript 错误TypeError: Cannot read property 'name' of null,vue 可能会将您显示为警告。你的 1 变种是好的。与您孩子的&lt;div v-if="person"&gt;{{person.name}}&lt;/div&gt; 相同。你也可以用像

      这样的东西来填充你的人
      return {
        person: {name: 'loading...'}
      }
      

      在你的父母中

      mounted: function () {
        // your person will be loaded when component mounted
        this.getPerson() 
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-23
        • 2019-01-19
        • 2016-04-01
        • 2021-03-16
        • 1970-01-01
        • 2020-08-02
        • 2016-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多