我的项目有以下设置:
window.school = {
"id": 1,
"users": [
{
"id": 0,
"name": "Adam Carter",
"work": "Unilogic",
"email": "adam.carter@unilogic.com",
"dob": "1978",
"address": "83 Warner Street",
"city": "Boston",
"optedin": true
},
{
"id": 1,
"name": "Leanne Brier",
"work": "Connic",
"email": "leanne.brier@connic.org",
"dob": "13/05/1987",
"address": "9 Coleman Avenue",
"city": "Toronto",
"optedin": false
}
],
"images": [
"img0.png",
"img1.png",
"img2.png"
],
"coordinates": {
"x": 35.12,
"y": -21.49
},
"price": "$59,395"
}
const app = new Vue({
router,
el: '#app',
data: {
school: school,
}
});
我的一个vue组件是School.vue
<template>
<div>
<input type="button" value="Update school data" v-on:click="update()">
</div>
</template>
<script>
export default {
props:[
'school',
],
methods: {
update: function() {
let url = `/api/v1/school/${this.school.id}/update`;
this.axios.get(url, this.decisions)
.then((res) => {
// WARNING IS THROWN IN HERE
this.school = res.data.school;
})
.catch((error) => {
console.log(error);
});
}
},
}
</script>
但是我收到以下警告:warning: Avoid mutating a prop directly
所以问题是,如何从Vue组件更新应用程序“学校”信息?我对Vue不太熟悉,我不知道我是否正在关注反模式或其他什么,非常感谢你的帮助。
答案 0 :(得分:0)
在父子关系中,数据仅通过道具从父级传递给子级。因此,您无法直接更改来自子级的父级数据。您必须发出让父母听的特定事件。
在使用组件School的父上下文中,将其与其他指令一起使用:
<div id="app">
<school v-on:update="updateSchool"></school>
</div>
将特定方法添加到父级:
const app = new Vue({
router,
el: '#app',
data: {
school: school,
},
methods: {
updateSchool (data) {
this.school = data
}
}
})
编辑School.vue脚本:
<script>
export default {
props:[
'school',
],
methods: {
update: function() {
let url = `/api/v1/school/${this.school.id}/update`;
this.axios.get(url, this.decisions)
.then((res) => {
this.$emit('update', res.data.school);
})
.catch((error) => {
console.log(error);
});
}
},
}
</script>