即使不建议,也需要直接更改Vue.js中的属性

时间:2019-11-11 16:25:23

标签: vue.js vuejs2

我有这个vue实例:

new Vue({

        el: '#content',

        data:{
            form: form
        },

        methods:{
            onSubmit()
            {
                this.form.submit();
            }
        }
    })

并且我已经声明了一个组件:

Vue.component('image-file-selector', {
        props:{
            label:{
                required: true
            },
            title:{
                required: true
            },
            model:{
                required: true
            }
        },
        template: `<div class="form-group">
                        <label class="bmd-label-floating">@{{ label }}</label> <br>
                        <div class="input-group">
                          <span class="input-group-btn">
                            <a :data-input="title" :data-preview="holderId" class="image-lfm btn btn-primary">
                              <i class="fa fa-picture-o"></i>  choose
                            </a>
                          </span>
                            <input :id="title" :name="title" class="form-control" type="text" v-model="model"
                                v-on:click="update">
                        </div>
                        <img :id="holderId" style="margin-top:15px;max-height:100px;">
                    </div>`,
        computed:{
            holderId(){
                return this.title + '-holder';
            }
        },
        methods:{
            update()
            {
                console.log('updating ...');
                this.model = $('#' + this.title).val(); // error occurrs here
            }
        }

    });

并且我已经像这样实例化了我的组件:

<image-file-selector label="banner" title="banner" :model="form.banner"></image-file-selector>

问题是我收到以下错误消息:“ 避免直接更改道具,因为每当父组件重新渲染时,该值就会被覆盖。而是使用基于道具值的数据或计算属性 >”。我已将vue实例的form.banner属性绑定到组件的model属性,因为更改模型时需要更新form.banner。当调用更新函数时,我需要更改模型。我无法将change事件绑定到我的输入元素,因为它会引起另一个语义错误。我不知道如何使用数据代替组件中的属性,而又不破坏form.model绑定

1 个答案:

答案 0 :(得分:0)

  1. 您可以将props值作为对象(然后可以在组件内部使用该对象)
  2. 就像说的错误一样,可以使用本地数据属性分配prop值并在组件中使用

    数据:{   模型://为它分配prop值 }