欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中的單向數(shù)據(jù)流原則詳解

 更新時(shí)間:2025年03月24日 09:41:07   作者:Hejjon  
這篇文章主要介紹了Vue中的單向數(shù)據(jù)流原則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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ò)誤的寫(xiě)法:

  • 子組件 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ò)誤的寫(xiě)法, 不能在子組件中直接修改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: '測(cè)試彈框',
      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ù)流的原則,即父組件通過(guò) prop 向下傳遞數(shù)據(jù)到子組件,而子組件應(yīng)該通過(guò)事件(如自定義事件)來(lái)通知父組件更新數(shù)據(jù),而不是直接修改 prop 的值。

正確的寫(xiě)法如下:

在子組件中取消按鈕的點(diǎn)擊事件中不修改 dialogVisible 屬性的值, 而是通過(guò) $emit 發(fā)送一個(gè)自定義事件 dialog-close, 在父組件中使用 @dialog-close 去申明處理這個(gè)事件. 代碼如下:

  • 子組件:

  • 父組件:

總結(jié)

在 Vue.js 中,單向數(shù)據(jù)流(One-Way Data Flow)是一個(gè)重要的設(shè)計(jì)理念,指的是數(shù)據(jù)從父組件通過(guò) props 向下傳遞給子組件,而子組件不能直接修改這些數(shù)據(jù)。

如果子組件需要修改數(shù)據(jù),應(yīng)該通過(guò)事件通知父組件,由父組件更新數(shù)據(jù)。這種機(jī)制確保了組件之間的關(guān)系清晰,易于維護(hù)。

相關(guān)文章

最新評(píng)論