像对象这样的道具的默认值不起作用
Posted
技术标签:
【中文标题】像对象这样的道具的默认值不起作用【英文标题】:Default value for props like an object didn't work 【发布时间】:2021-06-10 15:22:05 【问题描述】:我的情况很奇怪:
我的HomeComponent.vue
<template>
<div class="home">
<img src="../assets/logo.png" />
<HelloWorld :msg="msg" @update="inputUpdated" />
</div>
</template>
<script lang="ts">
import defineComponent from "vue";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src
import Message from "@/interfaces/message";
export default defineComponent(
name: "Home",
components:
HelloWorld,
,
setup(props, emit )
const msg: Message =
year: 2020,
;
function inputUpdated(value): void
console.log("Get Event : " + value);
return
msg,
inputUpdated,
;
,
);
</script>
我的HelloWorld.vue
<template>
<div class="hello">
<h1> msg.title in the year : msg.year </h1>
<button @click="increment">count is : count </button>
<div> pow(2, 3) </div>
<p>Edit <code>component</code> to test state is state.year </p>
</div>
</template>
<script lang="ts">
import defineComponent, ref, reactive, PropType from "vue";
import State from "@/interfaces/state";
import Message from "@/interfaces/message";
export default defineComponent(
name: "HelloWorld",
props:
msg:
type: Object as PropType<Message>,
required: true,
default: function ()
return
title: "Arrow Function Expression",
year: 2020,
;
,
,
,
setup(props, emit )
console.log(props);
const count = ref(0);
const state: State = reactive(
title: "",
year: 2020,
);
function pow(x: number, y: number): number
return Math.pow(x, y);
function increment(): void
console.log("Emit : Hello World");
emit("update", "Hello World");
count.value++;
return
count,
increment,
pow,
state,
;
,
);
</script>
接口Message
:
export interface Message
title?: string;
year?: number;
我遇到的问题是,即使我为msg
创建了一个default
道具也不起作用,也没有考虑在内。我有消息in the year :
。我对 props 值的默认值做错了什么?提前谢谢,对不起我的英语。
【问题讨论】:
【参考方案1】:您期望默认道具的属性与传递的道具合并。那是行不通的,意味着道具被修改了,道具不应该被修改。 default
属性仅在 no 属性被传递时使用(因此您不需要required
属性。)
您必须在将对象拆分为单独的道具之间做出决定:
props:
title: ...,
year: ...
或者使用计算来合并:
setup(props)
const msgDefault =
title: "Arrow Function Expression",
year: 2020,
;
const merged = computed(() =>
return Object.assign(, msgDefault, props.msg); // shallow merge
)
return merged
【讨论】:
谢谢@shob以上是关于像对象这样的道具的默认值不起作用的主要内容,如果未能解决你的问题,请参考以下文章