Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【vue 系列】props 传递对象时如何保留没有赋值的属性默认值 #5

Open
NoName4Me opened this issue Jun 6, 2018 · 0 comments
Labels
vue vue系列文章

Comments

@NoName4Me
Copy link
Owner

Vue 通过 props 给子组件传递对象数据时,如何保证在制定了一些属性时不覆盖其它属性的默认值?

props 简单回顾

props: ['a', 'b']

// or
props: {
  c: {
    type: Boolean,
    default: true
  }
}

回到问题

假设有一个组件 j-article,有一个名为 optionsprops

<template>
  <!-- a tiny demo -->
  <div>
    <h2>{{options.title}}</h2>
    <p>{{options.content}}</p>
    <p>{{options.format}}</p>
  </div>
</template>
<script>
export default {
  name: 'j-article',
  props: {
    'options': {
      type: Object,
      default: function() {
        return {
          title: '无题',
          content: '空内容',
          format: 'utf-8'
        }
      }
    }
  }
}
</script>

父组件调用:

<j-article :options="article"></j-article>
<script>
export default {
  data() {
    return {
      aritcle: {
        title: '打油诗'
      }
    }
  }
}
</script>

这种场景下会导致 options 的默认值(contentformat)被丢弃。解决:

<template>
  <div>
    <h2>{{options.title}}</h2>
    <p>{{options.content}}</p>
    <p>{{options.format}}</p>
  </div>
</template>
<script>
export default {
  name: 'j-article',
  props: {
    'options': {
      type: Object
    }
  },
  computed: {
    withDefaultOptions() {
      return Object.assign({
        title: '无题',
        content: '空内容',
        format: 'utf-8'
      }, this.options);
    }
  }
}
<script>

题外话: 对象增加属性使用 Vue.set() 或者 vm.$set(),这样才能正确监听到变化。

@NoName4Me NoName4Me added the vue vue系列文章 label Jun 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue系列文章
Projects
None yet
Development

No branches or pull requests

1 participant