v绑定数据未在vue组件模板中更新

问题描述 投票:0回答:1

当在vue组件中更新对象时,即使Dom与v-bind连接,Dom也不会更新。

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同步的字段。如果我在父级别而不是组件级别尝试,则可以使用相同的方法。

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

vue.js sails.js
1个回答
0
投票

要保持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
© www.soinside.com 2019 - 2024. All rights reserved.