1. 常用的方法

一般通过子组件修改父组件传递过来的值,我们就会采用props和$emit进行单向数据绑定

父组件:

<template>
    <div>
   		<test :value="value" @change="change"></test>
    </div>
</template>

<script>
import test from '@/components/test.vue'
export default {
	components: {
        test
    },
    data() {
        return {
        	value: '父组件的值'
        };
    },
    methods: {
        change (value) {
            this.value = value
        }
    }
}
</script>

子组件:

<template>
    <div>
    	<div>{{ value }}</div>
    	<button @click="change">改变父组件的值</van-button>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: String
        }
    },
    methods: {
        change () {
            this.$emit('change', '子组件调用父组件的change方法修改的')
        }
    },
};
</script>

2. 通过.sync修饰符在子组件中修改

父组件:

<template>
    <div>
   		<test :value.sync="value"></test>
    </div>
</template>

<script>
import test from '@/components/test.vue'
export default {
	components: {
        test
    },
    data() {
        return {
        	value: '父组件的值'
        };
    }
}
</script>

子组件:

<template>
    <div>
    	<div>{{ value }}</div>
    	<button @click="change">改变父组件的值</van-button>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: String
        }
    },
    methods: {
        change () {
            this.$emit('update:value', '在子组件中修改父组件的值')
        }
    },
};
</script>

3. 使用v-model双向数据绑定

父组件:

<template>
    <div>
   		<test v-model="value"></test>
    </div>
</template>

<script>
import test from '@/components/test.vue'
export default {
	components: {
        test
    },
    data() {
        return {
        	value: '父组件的值'
        };
    }
}
</script>

子组件:

<template>
    <div>
    	<div>{{ value }}</div>
    	<button @click="change">改变父组件的值</van-button>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: String
        },
    },
    model: {
    	prop: 'value',
    	event: 'changes'
    }
    methods: {
        change () {
            this.$emit('changes', '在子组件中修改父组件的值')
        }
    },
};
</script>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐