【问题标题】:Avoid props mutation in vueJS避免 vueJS 中的 props 突变
【发布时间】:2020-07-01 18:31:06
【问题描述】:

我有一个带有 props 的组件,我想将值从 false 修改为 true,但我有一个消息表单 chrome 控制台

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders

在父组件中,我有一个函数(myFunction),它接受一个参数(值)。

我需要像这样保持我的论点,但我还需要从子组件中检索 emit 的值以更改 myData 的值而不改变子组件中的道具。

https://codesandbox.io/s/distracted-wiles-w8vwf

<template>
  <div>
    <p>The number is {{number}}</p>
    <Child :MyProp="myData" @on-click-btn="myfonction(5)"/>
  </div>

</template>

<script>
import Child from "./components/Child.vue";

export default {
  data() {
    return {
      myData: 'button',
      number: 1
    };
  },
  components: {
    Child
  },
  methods: {
    myfonction(value) {
      this.number = value;
    }
  }
};
</script>

谢谢

【问题讨论】:

  • 这能回答你的问题吗? Vue 2 - Mutating props vue-warn
  • 不抱歉,谢谢
  • 你能分享代码吗,你在哪里遇到这个错误?
  • 我更新了我的代码。

标签: javascript vue.js


【解决方案1】:

在Vue中直接修改prop是一种反模式

相反,您可以使用 child 中的 emitevent 并修改作为 prop 传递给子级的父级中的数据,如下所示:

父.vue

<template>
  <child 
   MyProp="myData"
   @on-click-btn="handleClick" // [2] listen to the event & attach an handler to it
  />
</template>

export default {
 data () {
  return {
   myData: false
  }
 },
 // [3] event handler gets called when event is triggered ie. at user's click
 handleClick (currentValue) {
  // [4] modify the data, that is being passed as prop to the child, so that child recieves the updated data
  this.myData = !currentValue
 }
}

child.vue

<template>
  <button @click="handleClick">click me, I am {{ MyProp }}</button>
</template>

export default {
 props: ['MyProp'],
 method: {
  handleClick () {
   // [1] emit an event on user's click & pass the current prop value to it
   this.$emit('on-click-btn', this.MyProp)
  }
 }
}

demo

【讨论】:

  • 你能不能给我做个codepen,因为我很难跟着你,对不起
  • @TheDevGuy np,当然这里是笔:codesandbox.io/s/affectionate-chatelet-q2113
  • 我还有一个问题,我在父组件上使用了一个带参数的方法,他做了很多事情,那么如何在函数中获取道具的价值?
  • 是否要在 prop 更新时调用该方法?或者您希望何时调用该方法?
  • 如果您希望在更新道具时调用该方法,您可以简单地在父级中的handleClick fn 中调用您的方法并传递更新的this.myData(即您更新的道具值)到fn
【解决方案2】:

您可以使用sync 修饰符:

Vue.component('child', {
  template: '#child',
  props: {
    val: {
      type: String, required: true
    }
  },
  methods: {
    handleInput(event) {
      this.$emit('update:val', event.target.value)
    }
  }
})

new Vue({
  el: '#app',
  data(){
    return {
      value: ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<script type="text/x-template" id="child">
  <input @input="handleInput">
</script>

<div id="app">
  <child :val.sync="value"></child>
  <div>{{ value }}</div>
</div>

【讨论】:

  • 它,你喜欢不使用sync and update,然后使用&lt;child @val="value = $event"&gt;&lt;/child&gt;,当然删除update,同时发出this.$emit('val', event.target.value)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2018-06-04
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 2020-06-23
相关资源
最近更新 更多