在views文件夹创建EditLabel.vue文件,并添加路由
{path: '/labels/edit',component: EditLabel},
给tags数据添加id,以方便删除操作
const localStorageItemName = 'tagList';type tag = {id: stringname: string}type TagListModel = {data: tag[],fetch: () => tag[],create: (name: string) => 'success' | 'duplicated', // 联合类型save: () => void}const tagListModel: TagListModel = {data: [],fetch() {this.data = JSON.parse(window.localStorage.getItem(localStorageItemName) || '[]');return this.data;},create(name) {const names = this.data.map(item => item.name)if (names.indexOf(name) >= 0) {return 'duplicated';}this.data.push({id: name, name: name});this.save();return 'success';},save() {window.localStorage.setItem(localStorageItemName, JSON.stringify(this.data));}};export default tagListModel;
实现点击标签跳转至EditLabel页面
修改EditLabel路由,添加:id占位符, id是任意起的,可以是:xxx
{path: '/labels/edit/:id',component: EditLabel},
当浏览器输入http://localhost:8080/#/labels/edit/1时,则跳转至id为1的页面
使用this.$route.params.id可以获取到当前id的值
created(){const id = this.$route.params.idconsole.log(id);}
当标签不存在时,跳转至404页面
created(){const id = this.$route.params.idtagListModel.fetch()const tags = tagListModel.dataconst tag = tags.find(t => t.id === id)if (tag) {console.log(tag);} else {this.$router.replace('/404')}}
this.$router访问路由器, replace是替换当前不存在的地址,也可以用push方法,但是不存在的地址还在路由器中,导致无法回退
将Labels.vue中的li修改为router-link
<div class="tags"><router-link class='tag':to="`/labels/edit/${tag.id}`" v-for="tag in tags":key="tag.id"><span>{{ tag.name }}</span><Icon name="right"/></router-link></div>
将Notes改造成通用组件
添加2个props,refactor组件名为FromItem
将Button封装成通用组件
<template><button class="button" @click="$emit('click', $event)"><slot/></button></template>
button抛出click事件,传递给父组件
<Button @click="createTag">新建标签</Button>
现在在组件上使用 v-on 只会监听自定义事件 (组件用 $emit 触发的事件)。如果要监听根元素的原生事件,可以使用 .native 修饰符,比如:
