javascript - 使用 vue 组件时避免直接修改 prop

标签 javascript vue.js vuejs2 vue-component

我在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/

相关文章:

javascript - 嵌套多层 array.map()

javascript - 将 @font-face 样式表规则添加到 chrome 扩展

javascript - jQuery Datepicker 未被执行

javascript - v-for 的 VueJS forceUpdate 不工作

webpack - 如何使用 Webpack 导入 Chart.js

javascript - v-html 中的 Vue.js v-model

javascript - 如何在脚本中使用SQL查询

javascript - Vue.js 将函数作为 prop 传递并让 child 用数据调用它

javascript - Vue js 2 - 从子组件访问 App.vue 中的数据

javascript - 从 vue 导入 {ref} 时出错?