gpt4 book ai didi

javascript - Vue router 不会重新初始化子组件

转载 作者:行者123 更新时间:2023-11-28 14:07:02 25 4
gpt4 key购买 nike

我对 vue-router 有一个奇怪的问题。

我有一个供用户使用的简单 CRUD 应用程序。

它由四个不同的 View 组成:

  1. 用户列表和创建按钮
  2. 使用表单子(monad)组件创建 View ,该组件从created()内部的api获取字段。
  3. 用户显示 View
  4. 用户使用同等形式的子组件更新 View 。

如果我第一次进入 ID 为 1 的用户的编辑页面,一切都会变得非常顺利。但是,如果我返回并单击另一个用户并转到编辑页面,它将显示带有 id 1 的用户值的表单,并且没有新的 ajax 请求。

看来组件会被重用。我尝试为表单子(monad)组件提供不同的 :key 值,但没有成功。

<router-view :key="$route.fullPath"></router-view>

在路由器 View 上设置 key 也没有成功...

如果我重新加载浏览器,它将正确显示

这里是一个简单的例子:

我的路线:

import Index from "./views/Index";
import Show from "./views/Show";
import Edit from "./views/Edit";
import Create from "./views/Create";

export default [
{
path: '/admin/users',
name: 'users.index',
component: Index
},
{
path: '/admin/users/create',
name: 'users.create',
component: Create
},
{
path: '/admin/users/:id',
name: 'users.show',
component: Show,
props: true
},
{
path: '/admin/users/:id/edit',
name: 'users.edit',
component: Edit,
props: true
},
];

编辑组件(创建是没有id的sme):

<template>
<ResourceForm
resource="user"
:resource-id="id"
@cancel="$router.push({name: 'users.index'})"
/>
</template>

<script>
import ResourceForm from "../../../components/ResourceForm";

export default {
components: {ResourceForm},

props: ['id'],
}
</script>

ResourceForm 组件:

<template>
<form @submit.prevent="submitResourceForm">
<component
v-for="(field, index) in fields"
:key="field.name + index"
:ref="`${field.name}-field`"
:is="field.component"
:field="field"
:validation-errors="getValidationErrors(field)"
/>
<div class="mt-8 border-t border-gray-200 pt-5">
<div class="flex justify-end">
<span class="inline-flex rounded-md shadow-sm">
<button type="button" @click="$emit('cancel')"
class="py-2 px-4 border border-gray-300 rounded-md text-sm leading-5 font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800 transition duration-150 ease-in-out">
{{this.cancelText}}
</button>
</span>
<span class="ml-3 inline-flex rounded-md shadow-sm">
<button type="submit"
class="btn">
{{this.submitText}}
</button>
</span>
</div>
</div>
</form>
</template>
<script>
import _ from 'lodash';
import api from "../lib/api";
import Form from "../lib/mixins/Form";

export default {
mixins: [Form],
props: {
resource: {
type: String,
required: true
},
resourceId: {
required: false,
default: null
},
cancelText: {
type: String,
default: 'Cancel'
},
submitText: {
type: String,
default: 'Submit'
},
},
data() {
return {
fields: []
}
},
watch: {
'$route': function () {
console.log('route changed');
this.fetchResourceForm();
}
},
created() {
this.fetchResourceForm();
},
methods: {
async fetchResourceForm() {
let route;
if (this.resourceId !== null) {
route = Cms.route('cms.api.forms.show', {
resource: this.resource,
id: this.resourceId
});
} else {
route = Cms.route('cms.api.forms.new', {resource: this.resource});
}

const response = await api(route);
this.fields = response.data.data.fields;
},

async submitResourceForm() {
const formData = this.getFormData();

try {
const foo = {
...Cms.route('cms.api.forms.store', _.pickBy({
resource: this.resource,
id: this.resourceId
})),
data: formData
};
const response = await api(foo);

this.$emit('success', response.data.data);

} catch (error) {
if (error.response.status === 422) {
this.validationErrors = error.response.data.errors;
Cms.flash('error', 'There are validation errors in the form.')
}
}
}
}
}
</script>

Cms.route方法确实会生成api路由,与vue-router无关。

最佳答案

从任何父组件观察路由器。

watch:{
`$route`:function(route){
if(route.name === 'users.create'){
this.fetchData(route.params.id);
}
}
},
methods:{
fetchData:function(id){
// fetch your data corresponding to the id
// save the response to store using `commit`.
// this.$store.commit('SET_FIELDS',response.data.data.fields);
}
}

然后在存储中初始化变异状态

const state = {
fields:{}
}

const mutations = {
SET_FIELDS:(state,value)=>state.fields = value;
}

ResourceForm组件内,您可以使用compulated方法从store获取数据。

computed:{
fields:function(){
return this.$store.state.fields;
}
}

fields 值将在更改路线时实时呈现。

关于javascript - Vue router 不会重新初始化子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61028488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com