路由小幅重构;keep-alive更合理

master 1.2.0
yutent 2023-09-25 14:15:32 +08:00
parent 5e9dd986df
commit 1cddfb6731
3 changed files with 53 additions and 44 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "wkitd", "name": "wkitd",
"version": "1.1.3", "version": "1.2.0",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"files": [ "files": [

View File

@ -5,22 +5,7 @@ import { __ROUTER_VIEW__ } from '../constants.js'
class RouterView extends Component { class RouterView extends Component {
static props = { static props = {
transition: false, transition: false
current: {
type: String,
default: '',
attribute: false,
observer(v, old) {
if (this.keepAlive && v) {
if (old && this.$refs[old]) {
this.$refs[old].deactivated()
}
this.$refs[v]?.$requestUpdate()
this.$refs[v]?.$animate()
this.$refs[v]?.activated()
}
}
}
} }
static styles = css` static styles = css`
@ -29,6 +14,43 @@ class RouterView extends Component {
} }
` `
get current() {
return this.#current
}
set current(v) {
let old = this.#current
this.#current = v
if (this.keepAlive) {
if (old) {
if (this.$refs[old]) {
this.$refs[old].deactivated()
this.$refs[old].remove()
} else {
this.$requestUpdate()
}
} else {
this.$requestUpdate()
}
if (v) {
if (this.$refs[v]) {
this.root.appendChild(this.$refs[v])
this.$refs[v].$requestUpdate()
if (this.transition) {
this.$refs[v].$animate()
}
this.$refs[v].activated()
} else {
this.$requestUpdate()
}
}
} else {
this.$requestUpdate()
}
}
#current = ''
#views = [] #views = []
created() { created() {
@ -47,35 +69,21 @@ class RouterView extends Component {
{ transform: 'translateX(0)', opacity: 1 } { transform: 'translateX(0)', opacity: 1 }
] ]
} }
if (this.keepAlive) {
let template = this.#views.map(it =>
this.transition
? [
`<${it} ref="${it}" keep-alive #animation="%s" style="%s"></${it}>`,
[
{ ...option, immediate: this.current === it },
this.current === it ? '' : 'display:none'
]
]
: [
`<${it} ref="${it}" keep-alive style=%s></${it}>`,
[this.current === it ? '' : 'display:none']
]
)
return raw(
template.map(it => it[0]).join(''),
template.map(it => it[1]).flat()
)
} else {
if (this.current) { if (this.current) {
if (this.transition) { if (this.transition) {
return raw(`<${this.current} #animation="%s"></${this.current}>`, [ return raw(
option `<${this.current} ref="${this.current}" ${
]) this.keepAlive ? 'keep-alive' : ''
} } #animation="%s"></${this.current}>`,
return raw(`<${this.current}></${this.current}>`) [option]
)
} }
return raw(
`<${this.current} ref="${this.current}" ${
this.keepAlive ? 'keep-alive' : ''
}></${this.current}>`
)
} }
} }
} }

View File

@ -138,6 +138,7 @@ class Router {
let route = this.#tables.get('!') let route = this.#tables.get('!')
$view.current = route.name $view.current = route.name
this.#route = { path, name: route.name, params: {}, query: {} } this.#route = { path, name: route.name, params: {}, query: {} }
this.#exec(this.#route)
} }
} }