Vue子组件修改props报错: ’Avoid mutating a prop directly since the value will be ..‘解决方法

2,807 阅读1分钟

在开发的时候见到过几次控制台报warn,虽然不解决也没啥影响,但是看着糟心。网上看了看有的解决方法很复杂,直达在vue官网看到有解决方案,记录一下。 vue官网解决方案地址: v2.cn.vuejs.org/v2/guide/co…

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selectTab"

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。

这也是为什么我们推荐以 update:myPropName 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

this.$emit('update:title', newTitle)

开发中遇到的场景: 简单写个tab组件 父组件:

 <tab-switch 
    :tab-list="EXAMPLE_LIST"
    :select-tab.sync="selectExample"/>

子组件:

<template>
    <div class="tab-switch">
        <div
            v-for="(item, index) in tabList"
            :key="index"
            @click="changeTab(item)"
        >
            {{ item.label }}
        </div>
    </div>
</template>

<script>
export default {
    props: {
        tabList: {
            type: Array,
            require: true
        },
        selectTab: {
            type: String,
            require: true
        }
    },
    data () {
        return {
        }
    },
    methods: {
        changeTab(item) {
        // 只需要这么改父组件传来的值就不会报警告了
            this.$emit('update:selectTab', item.value)
        }
    }
}
</script>

简单记录,大佬看到轻喷。。。