Vue中的單向數(shù)據(jù)流原則詳解
Vue中的單向數(shù)據(jù)流原則
做一個(gè) ElementUI 彈框組件的二次封裝

- 效果如下:

點(diǎn)擊取消按鈕發(fā)現(xiàn)彈出如下報(bào)錯(cuò)信息

[Vue warn]: 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: "dialogVisible"
錯(cuò)誤的寫法:
- 子組件 MyDialog3.vue
<!-- 子組件 -->
<template>
<!-- elmentui 的 Dialog -->
<el-dialog :title=title
:visible="dialogVisible">
<span slot="footer" class="dialog-footer">
<el-button @click="handleCancel">取 消</el-button>
<el-button type="primary" @click="">確 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: "MyDialog3",
props: ['title', 'dialogVisible'],
methods: {
handleCancel() {
this.dialogVisible = false; // 這是錯(cuò)誤的寫法, 不能在子組件中直接修改props的值
}
}
}
</script>
<style scoped>
</style>- 父組件 MyDialog3Test.vue
<template>
<div>
<el-button @click="btnClick">點(diǎn)我彈框</el-button>
<MyDialog3
:title="headerText"
:dialog-visible="dialogShow">
</MyDialog3>
</div>
</template>
<script>
import MyDialog3 from "@/components/dialog3/MyDialog3";
export default {
name: "MyDialog3Test",
components: {MyDialog3},
data() {
return {
headerText: '測試彈框',
dialogShow: false,
}
},
methods: {
btnClick() {
this.dialogShow = true;
}
}
}
</script>
<style scoped>
</style>出現(xiàn)這個(gè)錯(cuò)誤的原因
是父子組件在進(jìn)行通信時(shí),子組件直接修改了 props的某個(gè)屬性的值。
在 Vue.js 中,直接修改 prop(屬性)的值是被嚴(yán)格禁止的,因?yàn)檫@會(huì)導(dǎo)致父子組件之間的數(shù)據(jù)流變得難以追蹤和調(diào)試。Vue 設(shè)計(jì)之初就采用了單向數(shù)據(jù)流的原則,即父組件通過 prop 向下傳遞數(shù)據(jù)到子組件,而子組件應(yīng)該通過事件(如自定義事件)來通知父組件更新數(shù)據(jù),而不是直接修改 prop 的值。
正確的寫法如下:
在子組件中取消按鈕的點(diǎn)擊事件中不修改 dialogVisible 屬性的值, 而是通過 $emit 發(fā)送一個(gè)自定義事件 dialog-close, 在父組件中使用 @dialog-close 去申明處理這個(gè)事件. 代碼如下:
- 子組件:

- 父組件:

總結(jié)
在 Vue.js 中,單向數(shù)據(jù)流(One-Way Data Flow)是一個(gè)重要的設(shè)計(jì)理念,指的是數(shù)據(jù)從父組件通過 props 向下傳遞給子組件,而子組件不能直接修改這些數(shù)據(jù)。
如果子組件需要修改數(shù)據(jù),應(yīng)該通過事件通知父組件,由父組件更新數(shù)據(jù)。這種機(jī)制確保了組件之間的關(guān)系清晰,易于維護(hù)。
相關(guān)文章
通過實(shí)例解析vuejs如何實(shí)現(xiàn)調(diào)試代碼
這篇文章主要介紹了通過實(shí)例解析vuejs如何實(shí)現(xiàn)調(diào)試代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
vue路由$router.push()使用query傳參的實(shí)際開發(fā)使用
在vue項(xiàng)目中我們用函數(shù)式編程this.$router.push跳轉(zhuǎn),用query傳遞一個(gè)對(duì)象時(shí)要把這個(gè)對(duì)象先轉(zhuǎn)化為字符串,然后在接收的時(shí)候要轉(zhuǎn)化為對(duì)象,下面這篇文章主要給大家介紹了關(guān)于vue路由$router.push()使用query傳參的實(shí)際開發(fā)使用,需要的朋友可以參考下2022-11-11
基于axios 的responseType類型的設(shè)置方法
今天小編就為大家分享一篇基于axios 的responseType類型的設(shè)置方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-10-10
vue限制輸入框只能輸入8位整數(shù)和2位小數(shù)的代碼
這篇文章主要介紹了vue限制輸入框只能輸入8位整數(shù)和2位小數(shù),文中我們使用v-model加watch 實(shí)現(xiàn)這一個(gè)功能,代碼簡單易懂,需要的朋友可以參考下2019-11-11
關(guān)于delete和Vue.delete的區(qū)別及說明
這篇文章主要介紹了關(guān)于delete和Vue.delete的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10

