我在vue中创建了一个警报组件,如下所示
<template>
<div class="alert-bg" v-if="view">
<div class="content">
<div class="message"> {{message}} </div>
<div class="alert-control text-right mt-4">
<button class="btn btn-secondary" @click="onCancel" v-html="cancel"/>
<button :class="btnStyle" class="btn ml-2" v-html="ok" @click="onSubmit"/>
</div>
</div>
</div>
</template>
<script>
import $ from 'jquery';
import 'imports-loader?window.jQuery=jquery,this=>window!widgster';
export default {
name: 'Alert',
props: {
message: { default: 'Lorem ipsum dolor sit amet consectetur' },
cancel: { default: 'Cancel' },
ok: { default: 'Yes' },
btnStyle: { default: 'btn btn-primary' },
view: { default: false }
},
methods: {
onCancel(){
this.view = false;
},
onSubmit(){
this.$emit('onSubmit');
}
},
};
</script>
然后在主页中我这样使用它,
// html
<button class="btn btn-secondary" @click="confirm" v-html="'Confirm'"/>
<Confirm :view="alert.view"/>
// script
import Confirm from '@/components/modals/alert/alert';
export default {
name: "Product",
components: { Confirm },
data() {
return {
alert: { view: false },
}
},
methods: {
confirm(){
this.alert.view = true; // show alert
}
}
}
当我点击确认按钮时,成功显示警报,当我点击取消按钮时,警报关闭,但出现这样的错误
[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: "view"
然后当我再次点击确认按钮时,警报没有出现,我该如何解决这个问题?非常感谢
最佳答案
您正在直接从子组件更改 prop(如 vue 所说)。 所以真正的方法是:
methods: {
onCancel(){
// this.view = false; <--- is wrong way
this.$emit('update:view', false)
}
// ...
},
然后在父级中像这样传递它:
<Confirm :view.sync="alert.view"/>
关于javascript - 使用 vue 组件时避免直接修改 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57584445/