v-bind 数据未在 vue 组件模板中更新

v-bind data not updating in vue component template

在 vue 组件中更新对象时,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 属性?

为了维护 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