如何在某些情况下更改数据?

时间:2017-12-21 08:51:41

标签: vue.js

我有parrrent和子组件。

在parrent组件中我有下一个代码

            <div v-for="(image, index) in images" class="col-md-4">
                <photo :index="index" :src ="image.src" :symbolId="image.symbol_id" :photoId="image.photo_id"></photo>
            </div>
    methods: {

        prepareCollage(){
            event.preventDefault();
            const self = this;
            axios.get('/api/prepare?query='+encodeURIComponent(this.text))
                .then(function(result){
                    const result_data = result.data;

                    if(result_data.error === true){
                        // here error code
                    }else{


                       self.images = result_data.images;

                    }

            });
        },

    }

和我的孩子组件

<template>
<div>
    <img v-on:click="replaceImage()" :src="mutatedSrc" class="img-responsive 
      image" :data-symbol-id="mutatedSymbolId" :data-photo-id="mutatedPhotoId">
    <input :name="mutatedIndex" :data-index="mutatedIndex" :data-symbol-id="mutatedSymbolId" :data-photo-id="mutatedPhotoId" type="hidden" :value="mutatedSrc">
</div>
</template>

<script>
    export default {
    name: 'photo',
    props: {
        src: {
            type : String,
            required: true
        },
        symbolId: {
            type: Number,
            required: true
        },
        photoId: {
            type: Number,
            required: true
        },
        index : {
            type: String,
            required: true
        }
    },
    data: function () {
        return {
            mutatedSrc: this.src,
            mutatedSymbolId: this.symbolId,
            mutatedPhotoId: this.photoId,
            mutatedIndex: this.index
        }
    },
    methods: {
        replaceImage(){
            const self = this;
            let arr_properties = { "sex" : 0, "nation" : 0, "color" : 0, "type" : 0};

            axios.get('/api/replace?photo_id='+this.mutatedPhotoId+'&symbol_id='+this.mutatedSymbolId+'&number='+this.mutatedIndex)
                .then(function(result){
                   self.mutatedSrc = result.data[0].photo_src;
                   self.mutatedPhotoId = result.data[0].photo_id;
                   self.mutatedSymbolId = result.data[0].photo_symbol_id;
                });
        }
    }
}

但在这种情况下,我的数据仅在调用函数replaceImage()时才会更改。当新的prop symbolId!= old prop symbolId。

时,我需要更改数据

例如我有下一个道具的照片:[src =&gt; 1.jpg,symbolId =&gt; 1,photoId =&gt; 1,index = 1]当我的父组件随下一个参数更改时[src =&gt; 2.jpg,symbolId =&gt; 2,photoId =&gt; 2,index = 2]我需要更改我的数据。

1 个答案:

答案 0 :(得分:0)

在道具上设置watch来设置道具中的data项目。

watch: {
  src(newValue) {
    this.mutatedSrc = newValue;
  },
  symbolId(newValue) {
    this.symbolId = newValue;
  },
  photoId(newValue) {
    this.mutatedPhotoId = newValue;
  },
  index(newValue) {
    this.mutatedIndex = newValue;
  }
}