We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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 给子组件传递对象数据时,如何保证在制定了一些属性时不覆盖其它属性的默认值?
props
props: ['a', 'b'] // or props: { c: { type: Boolean, default: true } }
假设有一个组件 j-article,有一个名为 options 的 props:
j-article
options
<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 的默认值(content 和 format)被丢弃。解决:
content
format
<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(),这样才能正确监听到变化。
Vue.set()
vm.$set()
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Vue 通过
props
给子组件传递对象数据时,如何保证在制定了一些属性时不覆盖其它属性的默认值?props
简单回顾回到问题
假设有一个组件
j-article
,有一个名为options
的props
:父组件调用:
这种场景下会导致
options
的默认值(content
和format
)被丢弃。解决:题外话: 对象增加属性使用
Vue.set()
或者vm.$set()
,这样才能正确监听到变化。The text was updated successfully, but these errors were encountered: