default
props 属性中的 default 选项用于设置 prop 的默认值。当父组件没有传入该 prop 时,Vue.js 将会使用默认值。这在确保组件在没有接收到必要的 prop 时仍能正常运行时非常有用。
new Vue({
el: '#app',
template: '<my-component></my-component>',
components: {
'my-component': {
props: {
// 如果父组件没有传递 str 属性,则默认为 'Hello, Vue!'
str: {
default: 'Hello, Vue!'
}
},
template: '<div>{{ str }}</div>'
}
}
});
default 选项在 Vue.js 的 props 中也可以接收一个函数作为默认值。这样做的好处是可以动态地生成默认值,而不是简单地返回一个静态的数值或对象。
new Vue({
el: "#app",
template: "<my-component></my-component>",
components: {
"my-component": {
props: {
// 如果父组件没有传递 str 属性,则默认为 'Hello, Vue!'
str: {
default: function () {
return "Hello, Vue!";
},
},
str2: {
default: () => "Hello, Vue2!",
},
},
template: "<div>{{ str }} - {{ str2 }}</div>",
},
},
});
注:可以使用箭头函数来定义默认值,但要注意箭头函数与普通函数在上下文绑定方面的区别。箭头函数没有自己的
this上下文,它会捕获定义时的上下文。
当默认值是对象或数组类型时,Vue.js 要求默认值必须从一个工厂函数获取。这是因为对象和数组是引用类型,在 Vue 组件中如果直接使用对象或数组作为默认值,会导致所有实例共享同一个对象或数组,从而产生意想不到的副作用。
new Vue({
el: "#app",
template: "<my-component></my-component>",
components: {
"my-component": {
props: {
// 使用工厂函数返回一个新的空对象作为默认值
config: {
type: Object,
default: function () {
return { key: "value" };
},
},
// 使用工厂函数返回一个新的空数组作为默认值
items: {
type: Array,
default: function () {
return [1, 2, 3];
},
},
},
template: "<div>{{ config.key }}, {{ items }}</div>",
},
},
});