【问题标题】:forceUpdate when component take props VueJS组件获取道具VueJS时的forceUpdate
【发布时间】:2019-03-02 19:19:45
【问题描述】:

我需要将 id 参数传递给我的组件并调用它的更新(重新渲染 -> 无需重新加载页面)

我有一个带有头像加载方法的组件

settings.vue

<template>
... download form and button with onUploadImg method 
</template>

<script>

methods: {
    onUploadImg() {
        if(this.avatarFile == null) return;
        var formData = new FormData();
        formData.append("file", this.avatarFile);        
        axios.post('urlForPost',
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(response => {
              //response Ok, show message and reload img on this page
               this.$nextTick(() => {
                   //Need send new FileId from image to MyVueAvatar.vue and update him
                   localStorage.setItem('picture', response.data); //can be through local storage?
               })
            })
            .catch(error => {
                 console.log(error);
      });
    }
}
</script>

OrderContainer.vue

<template>
    <my-vue-avatar class="img-avatar" :id="this.avatarPicId"></my-vue-avatar>
....
</template>
<script>
import MyVueAvatar from '../Avatar'
....
</script>

MyVueAvatar.vue(如果有新头像上传到settings.vue,需要更新这个组件)

<template>
    <div>
        <img :src="`data:image/png;base64, ${file}`" class="img-avatar" style="height: 35px;"  />
    </div>
</template>

<script>
import axios from 'axios'
export default  {
    props: {
        id: null
    },
    data: () => {
        return { 
            file: null
        }
    },
    created() {
        this.onGetImage(this.id);
    },
    methods: {
        onGetImage(id) {
            if (id == null) return;        
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('jwt');
            axios.get('url/File/Get/' + id,
            {
                responseType: 'arraybuffer'
            })
            .then(r =>
            {
                var buffer = new Buffer(r.data, 'binary').toString('base64');
                this.file = buffer;
            })
            .catch(error => {
                console.log(error);
            });
        }
    }
}
</script>

如何做到这一点?

【问题讨论】:

  • settings.vue 的父组件是谁?
  • 每次更改 prop id 时是否需要调用 onGetImage(id)
  • 是的,每次id 改变时我都需要打电话

标签: javascript node.js vue.js


【解决方案1】:

您传递给MyVueAvatarprops 应该是反应式的。 如果您仍然想在每次avatarPicId 更改时导致MyVueAvatar 的完全重新渲染,它有点hacky,但您可以使用v-if 指令导致延迟渲染/重新渲染您的子组件:

settings.vueorderContainer.vue之间建立连接, 你有几个选项可以做到这一点,这里有一个使用 vue eventBus 的例子:

Settings.vue 内,每当id 发生变化时:

this.$eventBus/*or whatever you named your eventBus*/.$emit('idChange',id);

另一方面,orderContainer.vue 将听取此更改:

//OrderContainer.vue

    <template>
        <my-vue-avatar v-if="hasID" class="img-avatar" :id="avatarPicId"></my-vue-avatar>
    ....
    </template>
    <script>
    import MyVueAvatar from '../Avatar'
    ....
    data(){
            return { 
                avatarPicId:'',
                hasID: false
            }
        },
    beforeMount(){
        this.$eventBus.$on('idChange',id => {
            //this fanction will get triggered every time an `idChange` event fires.
            //lets assign the new value to our `avatarPicId`:
            this.avatarPicId = id;
            this.hasID = !!this.avatarPicId; //assign a boolean to this.hasID, wether the accepted id isnt undefined,null,false or empty string.
            //this.avatarPicId is sent as props to `my-vue-avatar` child component.
            //it should re-evaluates itself. if its not happening, you can  
             //cause here a complete destruction of MyVueAvatar 
             //component:
              this.hasID = false;
              //and a re-rendering, after the destruction is completed:
              this.$nextTick(()=> this.hasID = true);
        })
    },
}
</script>

【讨论】:

  • 但是如何将新值从 settings.vue 传输到 OrderContainer.vue?
  • settings.vue 和 ORderContainer.vue 有什么关系?
  • 我的意思是 - 其中一个是另一个的父级(在这种情况下我们可以使用 vue 自定义事件系统或道具)或者它们在组件树中是否有不同的关系,在这种情况下我们将不得不通过更复杂的通信方式,例如vuex store或eventBus
  • 是的,我感兴趣的是如何实现从子组件到父组件给参数
  • 如果我有一个事件总线,我需要如何处理传入的通知? computed ?
猜你喜欢
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 2017-12-23
  • 2018-02-25
  • 1970-01-01
  • 2019-06-07
  • 2020-01-03
相关资源
最近更新 更多