如何使用 Prop 值初始化数据属性

gth*_*huo 7 vue.js vuejs2

在 VueJS 中仍然有点年轻,但我喜欢它的每一点。但现在,固定在某个地方。
我想data()使用通过props. 这样我以后就可以改变它们,因为不建议改变组件内的 props。事实上,官方文档推荐使用 prop 值初始化这个属性,如下所示:

{
props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}
Run Code Online (Sandbox Code Playgroud)

我有类似下面的内容:

<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>
Run Code Online (Sandbox Code Playgroud)

如上面的注释部分所示,初始化不成功。的值也不会this.department出现created()mounted()钩子或钩子中。请注意,我可以看到它是使用 Chrome Vue Devtools 定义的。所以我的问题是,我究竟应该如何data()使用props值初始化属性,或者哪种方法是解决此问题的最佳方法?

小智 -1

计算属性是提供 prop 的可变版本的最简单方法,但您可能不希望在更新 prop 时丢失数据。您可以使用显式手表。

\n\n
\n

观察者

\n\n

虽然计算属性在大多数情况下更合适,但有时需要自定义观察器。这就是为什么 Vue 提供了更通用的方法来通过监视选项来响应数据更改。当您想要执行异步或昂贵的操作来响应数据更改时,这非常有用。

\n
\n\n

当您想要执行异步或昂贵的\n操作来响应数据变化时,这非常有用。

\n