簡體   English   中英

如何制作顯示“重新渲染時道具被覆蓋”反模式的示例

[英]How to make a sample that shows the 'Props are overwritten when re-rendering' anti pattern

我想確信“重新渲染時 Props 被覆蓋”是一種反模式

const MyButton = Vue.extend({
  props: {
    obj: {}
  },
  template:
    "<button @click=\"obj.text = 'Value'+Math.round(Math.random()*100)\">Change text in child ({{obj.text}})</button>"
});

const app = new Vue({
  el: "#main",
  data: {
    obj: { text: "Value2" }
  },
  components: {
    MyButton
  },
  template: `
<div>
  <Button @click='obj.text = "Value"+Math.round(Math.random()*100)'>Change text in parent ({{obj.text}})</Button><br>
  <MyButton :obj='obj'/> 👈 Pressing here 'mutate' the prop. It is an anti-pattern (Props are overwritten when re-rendering). But it seems to work just fine, how to change this sample so it shows the anti-pattern problem? (https://eslint.vuejs.org/rules/no-mutating-props.html)
</div>`
});

更新代碼筆: https://codepen.io/SVSMITH/pen/LYrXRzW

誰能幫忙?

在您的示例中,您實際上並沒有改變道具,因為您發送給孩子的是對 object 的引用。此引用保持不變。 看看如果您將孩子中的模板代碼更改為:

"<button @click=\"obj = {}\">Change text in child ({{obj.text}})</button>"

然后你會看到 prop 被覆蓋了,子項的值與父項的值不同。 當父級更新值時,子級中更新的值將被覆蓋。 這可能會導致嚴重且難以發現的錯誤。 因此在子級中使用emit來更新父級中的值,這將通過 prop 更新子級值。

如果你有很多這樣的道具和發射物,你應該考慮使用像Pinia這樣的商店。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM