[英]Avoid props mutation in vueJS
我有一个带有道具的组件,我想将值从 false 修改为 true 但我有一个消息表单 chrome 控制台
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders
在父组件中,我有一个函数(myFunction)接受一个参数(值)。
我需要像这样保持我的论点,但我还需要从子组件中检索发射的值以更改 myData 的值而不改变 child.props 中的道具。
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>
谢谢
prop
是一种反模式相反,您可以从child
emit
一个event
并修改作为道具传递给孩子的父母中的数据,如下所示:
父.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
}
}
孩子.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)
}
}
}
您可以使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.