在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
属性?
答案 0 :(得分: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