【问题标题】:Vue js seems to be returning nested objects as strings?Vue js 似乎将嵌套对象作为字符串返回?
【发布时间】:2018-08-23 18:43:08
【问题描述】:

我有一个对象

   var user = {
      name:"test",
      number:"9666-0503",
      details:{
          test:"cannot_access_this",
          second_field:"nope_no_go"
      }
   }

我在 Vue JS 中调用一个动作

[TYPES.FETCH_USER]({ commit }) {
    api.get('user').then(({ data }) => {
        commit(TYPES.STORE_USER, data)
        console.log(data)
        // This returns perfectly fine and valid.  If I do 
        //console.log(data.details.test), I get the correect value
    }, (error) => {
        console.log(error)
    })
},

然后是突变

[TYPES.STORE_USER](state, data) {
    state.user = data
    localStorage.set("user", state.user)
},

在我的 getters 文件中

getUser: state => {
    return state.user
}

在我的组件中我正在做

computed: {
  ...mapGetters(["getUser"]),
},
mounted(){
   this.getData()
},
methods: {
  getData() {
    this.$store.dispatch(TYPES.FETCH_USER);
  }

}

在模板中

    <h1>{{getUser.name}}</h1><!-- this works -->
    <h2>{{getUser.number}}</h2><!-- this works -->
    <h3>{{getUser.details.test}}</h3> <!-- THIS FAILS!!-->

所以 getUser.details.test 失败了。但是......如果我只是这样做

    <h3>{{getUser.details}}</h3>

然后它会打印出似乎是详细信息对象的字符串版本??!像下面这样......

    <h3>{"test":"cannot_access_this","second_field":"nope_no_go"}</h3>

这是怎么回事!?

最奇怪的是,如果我在任何时候都只是 console.log(state.user),它会正确返回。并且是一个完整的对象。为什么当我在模板中访问它时,它是否对任何嵌套对象进行字符串化?

【问题讨论】:

  • 您正在调用 this.$store.dispatch(TYPES.FETCH_USER);,这将调用 TYPES.FETCH_USER 操作,而不是突变。此外,突变只有 state 对象作为第一个参数。你有{ state },它是一个包含state 属性的解构对象。因此,如果您实际上以某种方式调用了突变,那么您正在设置 state.state.user,这不是您想要的
  • 不抱歉,我用错了措辞,我正在呼吁采取行动。动作是 TYPES.FETCH_USER。我已经更改了我的代码以反映下面的答案。但是仍然不起作用.... :( 它似乎只适用于单级对象。任何嵌套都会返回这些对象的字符串版本
  • 是的,就像 acdcjunior 所说,最初,getUser 将被设置为 state.user 在您的 vuex 存储中初始化的值。 state.user 的初始值似乎很可能是一个空对象,因此尝试访问 state.user.details.test 会导致错误。最简单的解决方法是使用details 属性初始化state.user:state: { user: { details: {} } }

标签: javascript object vue.js


【解决方案1】:

Mutations must be synchronous.在突变中使用异步代码会产生各种无法追踪的怪异行为。

按照文档的建议,您应该将异步代码移动到 action,例如:

mutations: {
    [TYPES.FETCH_USER](state, data) {
        state.user = data
    }
    //...
},
actions: {
    fetchUsersActionName({ commit }) {
        return api.get('user').then(({ data }) => {
            commit(TYPES.FETCH_USER, data)
            console.log(data)
        }, (error) => {
            console.log(error)
        });
    }
}

并将其与.dispatch() 一起使用,而不是.commit(),例如:

this.$store.dispatch('fetchUsersActionName');

错误

查看以下演示以了解您收到错误的原因:

<h1>{{getUser.name}}</h1><!-- this works -->
<h2>{{getUser.number}}</h2><!-- this works -->
<h3>{{getUser.details.test}}</h3> <!-- THIS FAILS!!-->

第一个演示会引发错误,因为最初getUser.details.test 是undefined,因此它尝试访问undefined.test,从而引发错误:

var globalUser = {
  name:"test",
  number:"9666-0503",
  details:{
    test:"cannot_access_this",
    second_field:"nope_no_go"
  }
};
var TYPES = {FETCH_USER: 'TYPESFETCHUSER'};
   
const store = new Vuex.Store({
  strict: true,
  state: {user: {}},
  mutations: {
    [TYPES.FETCH_USER](state, data) {
      state.user = data
    }
  },
  actions: {
    fetchUsersActionName({ commit }) {
      setTimeout(() => commit(TYPES.FETCH_USER, globalUser, 2000)); // simmulate asynchronous code
    }
  },
  getters: {
    getUser: state => state.user
  }
});
new Vue({
  store: store,
  el: '#app',
  computed: {
    ...Vuex.mapGetters(['getUser']),
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() { this.$store.dispatch('fetchUsersActionName'); }
  }
})
span {font-family: monospace; font-weight: bold; color: red } h1,h2,h3 {font-size: medium; display: inline-block}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<span>This throws an error, because initially .details is undefined.</span>
<div id="app">
  <h1>{{getUser.name}}</h1> |
  <h2>{{getUser.number}}</h2> |
  <h3>{{getUser.details.test}}</h3>
</div>

没有.test就没有错误:

var globalUser = {
  name:"test",
  number:"9666-0503",
  details:{
    test:"cannot_access_this",
    second_field:"nope_no_go"
  }
};
var TYPES = {FETCH_USER: 'TYPESFETCHUSER'};
   
const store = new Vuex.Store({
  strict: true,
  state: {user: {}},
  mutations: {
    [TYPES.FETCH_USER](state, data) {
      state.user = data
    }
  },
  actions: {
    fetchUsersActionName({ commit }) {
      setTimeout(() => commit(TYPES.FETCH_USER, globalUser, 2000)); // simmulate asynchronous code
    }
  },
  getters: {
    getUser: state => state.user
  }
});
new Vue({
  store: store,
  el: '#app',
  computed: {
    ...Vuex.mapGetters(['getUser']),
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() { this.$store.dispatch('fetchUsersActionName'); }
  }
})
span {font-family: monospace; font-weight: bold; color: red } h1,h2,h3 {font-size: medium; display: inline-block}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<span>This throws no error, and prints the whole details object.</span>
<div id="app">
  <h1>{{getUser.name}}</h1> |
  <h2>{{getUser.number}}</h2> |
  <h3>{{getUser.details}}</h3>
</div>

解决方法:使用.test 但使用v-if:

var globalUser = {
  name:"test",
  number:"9666-0503",
  details:{
    test:"cannot_access_this",
    second_field:"nope_no_go"
  }
};
var TYPES = {FETCH_USER: 'TYPESFETCHUSER'};
   
const store = new Vuex.Store({
  strict: true,
  state: {user: {}},
  mutations: {
    [TYPES.FETCH_USER](state, data) {
      state.user = data
    }
  },
  actions: {
    fetchUsersActionName({ commit }) {
      setTimeout(() => commit(TYPES.FETCH_USER, globalUser, 2000)); // simmulate asynchronous code
    }
  },
  getters: {
    getUser: state => state.user
  }
});
new Vue({
  store: store,
  el: '#app',
  computed: {
    ...Vuex.mapGetters(['getUser']),
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() { this.$store.dispatch('fetchUsersActionName'); }
  }
})
span {font-family: monospace; font-weight: bold; color: red } h1,h2,h3 {font-size: medium; display: inline-block}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<span>This throws no error, because the v-if controls the displaying to only when .test is available.</span>
<div id="app">
  <h1>{{getUser.name}}</h1> |
  <h2>{{getUser.number}}</h2> |
  <h3 v-if="getUser.details">{{getUser.details.test}}</h3>
</div>

解决方法:使用.test,但使用user 初始化包括details 属性:

var globalUser = {
  name:"test",
  number:"9666-0503",
  details:{
    test:"cannot_access_this",
    second_field:"nope_no_go"
  }
};
var TYPES = {FETCH_USER: 'TYPESFETCHUSER'};
   
const store = new Vuex.Store({
  strict: true,
  state: {user: {details: {}}},   // <============ THIS IS THE IMPORTANT, notice the  {details: {}}
  mutations: {
    [TYPES.FETCH_USER](state, data) {
      state.user = data
    }
  },
  actions: {
    fetchUsersActionName({ commit }) {
      setTimeout(() => commit(TYPES.FETCH_USER, globalUser, 2000)); // simmulate asynchronous code
    }
  },
  getters: {
    getUser: state => state.user
  }
});
new Vue({
  store: store,
  el: '#app',
  computed: {
    ...Vuex.mapGetters(['getUser']),
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() { this.$store.dispatch('fetchUsersActionName'); }
  }
})
span {font-family: monospace; font-weight: bold; color: red } h1,h2,h3 {font-size: medium; display: inline-block}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<span>This throws no error, because the user initial value contains a "details" field already.</span>
<div id="app">
  <h1>{{getUser.name}}</h1> |
  <h2>{{getUser.number}}</h2> |
  <h3>{{getUser.details.test}}</h3>
</div>

为什么?

这是因为更新user的代码是异步的。

第一次尝试显示 {{ getUser.name }},getUser.name 的值是 undefined,所以它什么都不显示(因为 Vue 在 {{ undefined }} 时什么都不显示)。几毫秒后,getUser.name 被更新,然后开始显示name。它非常快,这就是为什么你会觉得它从来不是undefined。

{{ getUser.number }} 和 {{ getUser.details }} 也是如此。

另一方面,当它尝试显示{{ getUser.details.test }} 时,它会抛出一个错误,因为起初getUser.details 是undefined,所以当它尝试访问getUser.details.test 时,它实际上与@ 相同987654362@,这就是它抛出TypeError: Cannot read property 'test' of undefined的原因。

对于变通方法,使用v-if 或使用非undefined details 属性初始化user(参见上面的最后两个演示)。

【讨论】:

  • 对不起,我不关注,模板将对象字符串化以显示它们。是这个问题吗?
  • 不,它将整个对象串起来。显示那个。但是,如果我尝试访问这些属性,它会显示未定义。所以 {{user.details.test}} 是未定义的。但是 {{user.details}} 将 '{"test":"data","second_field":"more_data"}' 作为字符串回显。但我无法将 test 或 second_field 作为对象访问。它们在那个细节字符串中,作为一个字符串,而不是一个对象。它唯一发生这种情况的嵌套对象。返回没有嵌套的对象,我可以很好地访问它们
  • 是因为代码是异步的。第一次尝试加载时,getUser.name 是 undefined,所以它什么都不显示。几毫秒后,getUser.name 被更新,然后开始处理name。 getUser.number 和 getUser.details 也是如此。 OTOH,当你输入{{ getUser.details.test }} 时,它会抛出一个错误,因为首先getUser.details 是undefined 而undefined.test 是一个错误。
  • 是的,但为什么它输出一个字符串?它不是未定义的。它是一个字符串
  • 看看演示,特别是最后一个,v-if。
猜你喜欢
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 2015-10-24
  • 2021-03-12
相关资源
最近更新 更多