我有两个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>
动物可以很好地显示:
但是我在控制台中收到警告:
明确分配道具的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}
可以确保它是自动分配的,但事实并非如此。我该如何解决?
答案 0 :(得分:2)
Well updating prop directly is an antipattern
当animal
组件中不包含DisplayAnimal
道具时,如果您知道它不是将数据传递给它的父组件的一部分,也没有任何意义。 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;
}