在Vue中,我们可以通过this.$emit()来触发自定义事件并传递数据。如果要修改Props的值,需要先将其作为本地变量进行存储,然后再使用$emit()来更新该属性的值。
下面是一个示例代码:
- // 子组件 Child.vue
- <div>{{ propValue }}div>
-
- <script>
- export default {
- props: ['propName'], // 接收名为propName的Prop
-
- data() {
- return {
- localPropValue: this.propName // 将Prop的初始值保存到localPropValue中
- }
- },
-
- methods: {
- updateProp(newVal) {
- this.localPropValue = newVal; // 更新localPropValue的值
-
- // 调用父组件传递的updateEvent事件,并传递新的值
- this.$emit('updateEvent', newVal);
- }
- }
- }
- script>
- <template>
- <child :prop-name="parentProp" @updateEvent="handleUpdate">child>
- template>
-
- <script>
- import Child from './Child.vue';
-
- export default {
- components: {
- Child
- },
-
- data() {
- return {
- parentProp: 'initial value' // 设置父组件的Prop值
- };
- },
-
- methods: {
- handleUpdate(updatedValue) {
- console.log("Updated Prop Value:", updatedValue);
- this.parentProp = updatedValue; // 更新父组件的Prop值
- }
- }
- };
- script>
这样就能够在子组件中修改Props的值了。当子组件内部的updateProp()被调用时,会触发@updateEvent事件,从而将新的值传递给父组件的handleUpdate()方法,最终更新父组件的Prop值。