【发布时间】:2020-02-04 22:45:15
【问题描述】:
我有一个属性需要传递给子组件,但子组件需要能够修改传递的值。似乎.sync 修饰符是为此而构建的,但我似乎无法让它工作。这是我的代码(针对这个问题进行了简化):
Profile.vue
<template>
<div>
<Avatar :editing.sync="editing"></Avatar>
<a href="" @click.prevent="changeAvatar">click to change</a>
...
</div>
</template>
<script>
import Avatar from './profile/Avatar'
export default {
components: { Avatar },
data() {
return {
...,
editing: false,
}
},
methods: {
editAvatar() {
this.editing = true;
}
}
}
</script>
头像.vue
<template>
<div>
<template v-if="!editing">
<img class="avatar-preview" :src="avatar">
</template>
<template v-else>
<label v-for="image in avatars">
<img class="avatar-thumb" :src="image">
<input type="radio" name="avatar" :checked="avatar === image">
</label>
<button class="btn btn-primary">Save</button>
</template>
</div>
</template>
<script>
export default {
props: ['editing'],
data() {
return {
avatar: '../../images/three.jpg',
avatars: [
'../../images/avatars/one.jpg',
'../../images/avatars/two.jpg',
'../../images/avatars/three.jpg',
...
]
}
},
methods: {
save() {
axios.put(`/api/user/${ user.id }/avatar`, { avatar: this.avatar }
.then(() => { console.log('avatar saved successfully'); })
.catch(() => { console.log('error saving avatar'); })
.then(() => { this.editing = false; }); // ← this triggers a Vue warning
}
}
}
</script>
【问题讨论】: