【问题标题】:v-bind data not updating in vue component templatev-bind 数据未在 vue 组件模板中更新
【发布时间】:2020-05-20 01:20:08
【问题描述】:

当 vue 组件中的 Object 更新时,Dom 并没有更新,即使它与 v-bind 连接。

parasails.registerComponent('recipe-form', {
    //  ╔═╗╦═╗╔═╗╔═╗╔═╗
    //  ╠═╝╠╦╝║ ║╠═╝╚═╗
    //  ╩  ╩╚═╚═╝╩  ╚═╝
    props: [
      'recipe' //this is an object like {name: 'name', ingredientPhoto: '/images/no-image.png' }
    ],

    template: `
<ajax-form :action="currentPath === '/recipes/create-recipe' ? 'createRecipe' : 'updateRecipe'"
               :syncing.sync="syncing" :cloud-error.sync="cloudError" v-on:submitted="submittedForm($event)"
               :handle-parsing="handleParsingForm">

<!--- some html removed for clarity ---->

<div class="card">
              <img id="ingredient-photo-thumbnail" v-if="recipe.ingredientPhoto" class="thumbnail w-100" v-bind:src="recipe.ingredientPhoto" alt="Card image cap">
              <div class="card-body">
                <div class="input-group mb-2">
                  <div class="custom-file">
                    <input type="file" class="custom-file-input" name="ingredient-photo" id="ingredient-photo-input" accept="image/*"
                           @change="uploadFile('ingredientPhoto', $event)">
                    <label class="custom-file-label" for="custom-file-input">Ingredients Photo</label>
                  </div>
                </div>
              </div>
            </div>

<!--- src attribute does not change when recipe.ingredientPhoto is updated in method ---->

</ajax-form>
`,


    methods: {

      async uploadFile(photoType, event) {
        //simplified for clarity
        this.recipe.ingredientPhoto = `https://example.com/photo.jpg`;
        console.log(this.recipe); //this is logging the updated recipe.ingredientPhoto property as expected but it's not updating the img src in Dom
      }
    })
}

我不明白为什么它会更新数据对象属性recipe.ingredientPhoto,而不是更新与v-bind 同步的字段。如果我在父级别而不是组件级别尝试相同的方法。

recipe.ingredientPhoto 更新时,如何更新src 属性?

【问题讨论】:

  • 您的组件不应更新其props。这不是 Vue 的单向数据流的工作方式。父组件是什么样的? recipe 属性传递了什么值?
  • 你不应该在你的组件中本地改变道具,尝试使用计算或观察者

标签: vue.js sails.js


【解决方案1】:

要维护one-way data flow,您的组件应该将新的图像 URL 值发送到可以进行适当更改的父级。

例如,在父级中

<recipe-form :recipe="recipe" @uploaded="uploaded"></recipe-form>
data: () => ({
  // make sure all required properties are defined
  recipe: {
    ingredientPhoto: null // or whatever makes sense as a default value
  }
}),
methods: {
  uploaded (photoUrl) {
    this.recipe.ingredientPhoto = photoUrl
  }
}

在你的组件的uploadFile 方法中

this.$emit('uploaded', 'https://example.com/photo.jpg') // from your example

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2021-06-20
    • 1970-01-01
    • 2020-12-15
    • 2016-11-12
    相关资源
    最近更新 更多