15、TheResources.vue中添加deleteResource方法,并加到provide()中;然后在LearningResource.vue中使用(如果缺少id,需要props中添加id)
TheResources.vue
<template>
<base-card>
<base-button @click="selectTab('stored-resources')" :mode="storedResButtonMode">Stored Resources</base-button>
<base-button @click="selectTab('add-resource')" :mode="addResButtonMode">Add Resource</base-button>
</base-card>
<keep-alive>
<component :is="selectedTab"></component>
</keep-alive>
</template>
<script>
import StoredResources from "@/components/learning-resources/StoredResources.vue";
import AddResource from "@/components/learning-resources/AddResource.vue";
export default {
components: {
StoredResources,
AddResource,
},
computed: {
storedResButtonMode() {
return this.selectedTab === "stored-resources" ? null : 'flat';
},
addResButtonMode() {
return this.selectedTab === "add-resource" ? null : 'flat';
}
},
methods: {
selectTab(tab) {
this.selectedTab = tab;
},
addNewResource(title, description, link) {
const newResource = {
id: this.storedResources.length + 1,
title: title,
description: description,
link: link
};
//this.storedResources.push(newResource); //add new resource to the end of the list
this.storedResources.unshift(newResource); //add new resource to the beginning of the list
this.selectTab('stored-resources');
},
deleteResource(id) {
//和其它组件公用的是resourcesParams,所以改变storedResources不会看到删除生效
//this.storedResources = this.storedResources.filter(resource => resource.id !== id);
const resIndex = this.storedResources.findIndex(resource => resource.id === id);
this.storedResources.splice(resIndex, 1);
},
},
provide() {
return {
resourcesParams: this.storedResources,
addNewResource: this.addNewResource,
deleteResource: this.deleteResource,
};
},
data() {
return {
selectedTab: "stored-resources",
storedResources: [
{
id: 'official-guide',
title: 'Official Guide',
description: 'The official guide for using Vue.js.',
link: 'https://vuejs.org/guide/',
},
{
id: 'api-reference',
title: 'API Reference',
description: 'The API reference for using Vue.js.',
link: 'https://vuejs.org/api/',
},
{
id: 'examples',
title: 'Examples',
description: 'A list of examples for using Vue.js.',
link: 'https://vuejs.org/examples/',
}
]
};
},
};
</script>
LearningResource.vue
<template>
<li>
<base-card>
<header>
<h3>{{ title }}</h3>
<base-button mode="flat" @click="deleteResource(id)">Delete</base-button>
</header>
<p>{{ description }}</p>
<nav>
<a :href="link">View Resource</a>
</nav>
</base-card>
</li>
</template>
<script>
export default {
props: ['id','title', 'description', 'link'],
inject: ['deleteResource'],
}
</script>
<style scoped>
li {
margin: auto;
max-width: 40rem;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
}
h3 {
font-size: 1.25rem;
margin: 0.5rem 0;
}
p {
margin: 0.5rem 0;
}
a {
text-decoration: none;
color: #ce5c00;
}
a:hover,
a:active {
color: #c89300;
}
</style>