解決vue3報錯:Unexpected?mutation?of?“xxx“?prop.(eslintvue/no-mutating-props)
eslint校驗報這個錯,其實是Vue的單向數(shù)據(jù)流的概念,因為識別到子組件中修改了props值。
我這里踩到這個坑是這么操作的,我在父組件中給子組件傳了個值,然后再子組件中v-modle這個值,于是就給我報了這個錯!
復(fù)現(xiàn)場景如下:
父組件中
<enter-school ref="enterSchoolRef" :student-info="selectRows" />
子組件中
<template> <el-form ref="formRef" class="enterForm" inline :model="form" :rules="rules" @submit.prevent> <el-input v-model="studentInfo[0].name" clearable placeholder="請輸入姓名" /> </el-form> </template> <script> props: { studentInfo: { type: Array, //類型 default: null //默認值 }, }, </script>
報錯就在v-model="studentInfo[0].name"
不應(yīng)該在子組件中直接雙向綁定父組件傳遞過來的值
解決方案:
- 計算屬性 依賴該props進行計算/轉(zhuǎn)換
<template> <el-input v-model="studentName" clearable placeholder="請輸入姓名" /> </template> <script> import { computed } from 'vue' props: { studentInfo: { type: Array, //類型 default: null //默認值 }, } setup(props) { const studentName = computed(() => props.studentInfo && props.studentInfo.length > 0 ? props.studentInfo[0].name : null ) return { studentName } } </scirpt>
- 定義中間變量 在子組件內(nèi)的定義一個變量,并將接收的props當作其初始值:
<template> <el-input v-model="studentName" clearable placeholder="請輸入姓名" /> </template> <script> import { computed, defineComponent, reactive, toRefs } from 'vue' props: { studentInfo: { type: Array, //類型 default: null //默認值 }, } export default defineComponent({ setup(props) { const state = reactive({ studentName : props.studentInfo[0].name }) return { ...toRefs(state), } } }) </scirpt>
我就是用的方案1,搞個計算屬性解決了
總結(jié)
到此這篇關(guān)于解決vue3報錯:Unexpected mutation of “xxx“ prop.(eslintvue/no-mutating-props)的文章就介紹到這了,更多相關(guān)Unexpected mutation of “xxx“ prop內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解Vue父子組件生命周期執(zhí)行順序及鉤子函數(shù)
本文通過實例代碼給大家介紹了Vue父子組件生命周期執(zhí)行順序及鉤子函數(shù)的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-08-08vue-cli項目使用mock數(shù)據(jù)的方法(借助express)
現(xiàn)如今前后端分離開發(fā)越來越普遍,前端人員寫好頁面后可以自己模擬一些數(shù)據(jù)進行代碼測試,這樣就不必等后端接口,提高了我們開發(fā)效率。今天就來分析下前端常用的mock數(shù)據(jù)的方式是如何實現(xiàn)的,需要的朋友可以參考下2019-04-04Element Cascader 級聯(lián)選擇器的使用示例
這篇文章主要介紹了Element Cascader 級聯(lián)選擇器的使用示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07vuejs+element UI table表格中實現(xiàn)禁用部分復(fù)選框的方法
今天小編就為大家分享一篇vuejs+element UI table表格中實現(xiàn)禁用部分復(fù)選框的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09