我有两个 vue
组件:GetAnimal.vue
和 DisplayAnimal.vue
。 GetAnimal.vue
使用路由器推送将包含动物数据的 JSON 发送到 DisplayAnimal.vue
。 DisplayAnimal.vue
显示该数据。它的工作原理如下:我转到 /getanimal
,单击一个触发 getAnimal()
函数的按钮,该函数将引导我到 /viewanimal
(通过路由器推送):
GetAnimal.vue:
<script>
import axios from 'axios';
export default {
data: function () {
return {
name: 'defaultAnimal',
defaultanimal: {
name: 'Cat',
furColor: 'red',
population: '10000',
isExtinct: false,
isDomesticated: true
},
animal: String
}
},
methods: {
getAnimal: function () {
console.log("this.defaultanimal: " +
JSON.stringify(this.defaultanimal));
this.$router.push({
name: "viewanimal",
params: {
animal: this.defaultanimal
}
});
},
...
DisplayAnimal.vue:
<template>
<div>
<h1>Displaying animal:</h1>
<p>Animal name: {{animal.name}}}</p>
<p>Fur color: {{animal.furColor}}</p>
<p>Population: {{animal.population}}</p>
<p>Is extinct: {{animal.isExtinct}}</p>
<p>Is domesticated: {{animal.isDomesticated}}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
props: {
animal: {
name: {
type: String
},
furColor: {
type: String
},
population: String,
isExtinct: String,
isDomesticated: String
}
},
name: "DisplayAnimal",
methods: {
},
created() {
console.log("animal param: " +
JSON.stringify(this.$route.params.animal));
this.animal = this.$route.params.animal;
}
};
</script>
动物显示得很好:
但是我在控制台中收到警告:
显式分配 props 的 this.animal = this.$route.params.animal;
行可能是导致警告的原因。
但是,如果我删除该行,动物根本不会显示:
我有这个
router.js:
{
path: "/viewanimal",
name: "viewanimal",
component: () => import('./views/DisplayAnimal.vue'),
props: {animal: true}
},
{
path: "/getanimal",
name: "getanimal",
component: () => import('./views/GetAnimal.vue')
}
我认为设置 props: {animal: true}
可以确保它是自动分配的,但事实似乎并非如此。我应该如何修复它?
最佳答案
Well updating prop directly is an antipattern
当您知道 DisplayAnimal
组件中的 animal
属性不是向其传递数据的父组件的一部分时,它也是没有意义的。 animal
应位于 data
内,以便您可以在 created
回调中进行更新。
示例
data() {
return {
loading: true, // perhaps you'd like to show loader before data gets fetched
animal: {
id: -1,
name: '',
furColor: '',
population: 0,
isExtinct: false,
isDomesticated: false
}
}
},
created() {
this.animal = this.$route.params.animal;
this.loading = false;
}
关于javascript - Vue : props doesn't get assigned automatically; when assigned manually - Avoid mutating a prop directly - error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62086757/