【发布时间】:2017-08-29 16:05:09
【问题描述】:
在 VueJS 中仍然有点年轻,但我喜欢它的每一点。但现在,固定在某个地方。
我想使用通过props 传递的值初始化data() 中的一些值。这样我就可以在以后改变它们,因为不建议在组件内改变 props。事实上official docs 推荐使用prop 值初始化这个属性,如下所示:
{
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
我有类似下面的东西:
<template>
<div class="well">
<!-- Use Prop value directly on the template: works (but of no help in initializing data) -->
Department: {{department.name}}
<!-- Use prop value but gotten via computed property: Works inside the template but not in the initialization -->
Department: {{fetchDepartment.name}}
<!-- Use the array I initialized with the prop value: Does not work -->
Department: {{this_department.name}}
</div>
</template>
<script>
export default {
name: 'test',
props: ['department'],
data() {
return {
this_department: this.department
// below does not work either
//this_department: this.fetchDepartment
}
},
created() {
// shows empty array
console.log(this.department)
},
mounted() {
// shows empty array
console.log(this.department)
},
computed: {
fetchDepartment() {
return this.department
}
}
}
</script>
从上面的注释部分可以看出,初始化不成功。 this.department 的值也不会出现在 created() 或 mounted() 挂钩中。请注意,我可以看到它是使用 Chrome Vue Devtools 定义的。所以我的问题是,我应该如何使用 props 值初始化 data() 属性,或者哪种是解决这个问题的最佳方法?
【问题讨论】:
-
department是异步填充的吗?你在做什么是正确的。但如果它是异步的,那么初始化的值将是 null 并且不会被更新。在这种情况下,计算是正确的方法。 -
<test :department="department"></test>,其中department定义明确。虽然不确定你所说的异步是什么意思 -
你是否从 API 中获得价值?
-
好提示。让我检查一下,我会回来的:-)