【发布时间】: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属性传递了什么值? -
你不应该在你的组件中本地改变道具,尝试使用计算或观察者