vue新增默认值怎么设置
时间: 2023-10-25 18:12:27 浏览: 155
在 Vue 中,你可以使用 v-bind
指令绑定组件的属性,然后使用 JavaScript 表达式来设置默认值。如果绑定的值为 undefined
或 null
,则会使用表达式的默认值。
例如,假设你有一个 MyComponent
组件,它有一个 text
属性,你可以在组件中设置默认值如下:
<template>
<div>{{ text }}</div>
</template>
<script>
export default {
props: {
text: {
type: String,
default: 'Hello, world!' // 设置默认值为 'Hello, world!'
}
}
}
</script>
这样,当你在父组件中使用 MyComponent
时,如果不传递 text
属性,它会显示默认值 'Hello, world!'
。
<template>
<div>
<my-component></my-component>
<my-component text="Welcome to Vue"></my-component>
</div>
</template>
<script>
import MyComponent from './MyComponent.vue'
export default {
components: {
MyComponent
}
}
</script>
相关推荐















