v-bind,@input方式
<!-- 父组件 -->
<template>
<div>
<child-component
:value="parentValue"
@input="parentValue = $event"
></child-component>
<p>父组件的值: {{ parentValue }}</p>
</div>
</template>
<script>
import ChildComponent from "../components/ChildComponent.vue";
export default {
components: {
ChildComponent,
},
data() {
return {
parentValue: "默认值",
};
},
};
</script>
<!-- 子组件 -->
<template>
<div>
<input v-model="childValue" />
</div>
</template>
<script>
export default {
props: ["value"],
computed: {
childValue: {
get() {
return this.value; // 从父组件获取值
},
set(newVal) {
this.$emit("input", newVal); // 向父组件提交更新
},
},
},
};
</script>
computed方式
<!-- 父组件 -->
<template>
<div>
<child-component v-model="parentValue"></child-component>
<p>父组件的值: {{ parentValue }}</p>
</div>
</template>
<script>
import ChildComponent from "../components/ChildComponent.vue";
export default {
components: {
ChildComponent,
},
data() {
return {
parentValue: "默认值",
};
},
};
</script>
<!-- 子组件 -->
<template>
<div>
<input v-model="childValue" />
</div>
</template>
<script>
export default {
props: ["value"],
computed: {
childValue: {
get() {
return this.value; // 从父组件获取值
},
set(newVal) {
this.$emit("input", newVal); // 向父组件提交更新
},
},
},
};
</script>
.sync方式
<!-- 父组件 -->
<template>
<div>
<child-component :my-prop.sync="parentValue"></child-component>
<p>父组件的值: {{ parentValue }}</p>
</div>
</template>
<script>
import ChildComponent from "../components/ChildComponent.vue";
export default {
components: {
ChildComponent,
},
data() {
return {
parentValue: "默认值",
};
},
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="updateValue">修改prop</button>
</div>
</template>
<script>
export default {
props: ["myProp"],
methods: {
updateValue() {
this.$emit("update:myProp", "新值");
},
},
};
</script>