Vuex 상태에서 Vue 라우터를 사용하는 방법?
사용 중인 구성 요소:
this.$router.push({ name: 'home', params: { id: this.searchText }});
경로를 변경하다.나는 이제 내 Vuex의 행동으로 방법을 옮겼으며, 물론this.$router
더 이상 작동하지 않는다.또한 그렇지 않다.Vue.router
그럼, Vuex 주에서 라우터 메소드를 어떻게 부르지?
라우터 인스턴스가 필요해서 vuex-router-sync가 도움이 안 될 것 같아.
따라서 이것이 이상적으로 느껴지지는 않지만 웹 팩 내에서 해당 인스턴스를 전역으로 설정할 수 있다.
global.router = new VueRouter({
routes
})
const app = new Vue({
router
...
이제 다음을 수행할 수 있어야 함:router.push({ name: 'home', params: { id: 1234 }})
앱 내 어디에서나
만약 당신이 위의 아이디어를 좋아하지 않는다면 당신은 당신의 행동에서 약속을 돌려줄 수 있다.그럼 그 행동이 성공적으로 완료되면 돌연변이 같은 걸 부를 수 있을 거야resolve
약속하지만 실패하거나 리디렉션에 필요한 조건이 있으면reject
약속
이렇게 하면 라우터를 단순히 거부된 약속을 포착하고 vue-router 푸시를 실행하는 구성 요소로 리디렉션할 수 있다.
# vuex
actions: {
foo: ({ commit }, payload) =>
new Promise((resolve, reject) => {
if (payload.title) {
commit('updateTitle', payload.title)
resolve()
} else {
reject()
}
})
# component
methods: {
updateFoo () {
this.$store.dispatch('foo', {})
.then(response => { // success })
.catch(response => {
// fail
this.$router.push({ name: 'home', params: { id: 1234 }})
})
상황이 생겨서, 난 내 자신을 사용할 수 있어..go
대신에.push
.
미안한데, 왜 그런지 설명이 안 돼. 하지만 내 경우엔 잘 먹혔어.나 같은 미래의 구글러들을 위해 이것을 남겨둔다.
믿어요rootState.router
당신이 합격했다고 가정할 때 당신의 행동에 이용가능할 것이다.router
당신의 주요 Vue 생성자의 옵션으로.
GuyC가 언급했듯이, 나는 또한 당신이 당신의 행동에 대한 약속을 반납하고 그것이 해결된 후에 라우팅하는 것이 더 나을지도 모른다고 생각하고 있었다.간단히 말해서:dispatch(YOUR_ACTION).then(router.push())
.
state: {
anyObj: {}, // Just filler
_router: null // place holder for router ref
},
mutations: {
/***
* All stores that have this mutation will run it
*
* You can call this in App mount, eg...
* mounted () {
* let vm = this
* vm.$store.commit('setRouter', vm.$router)
* }
*
setRouter (state, routerRef) {
state._router = routerRef
}
},
actions: {
/***
* You can then use the router like this
* ---
someAction ({ state }) {
if (state._router) {
state._router.push('/somewhere_else')
} else {
console.log('You forgot to set the router silly')
}
}
}
}
갱신하다
내가 이 대답을 발표한 후 나는 내가 제시했던 것처럼 그것을 정의하는 것이 다음 필드들의 탐지를 멈추는 것을 알아챘다.state
. 그건 내가 사용했기 때문일 것이다.any
한 종류로아마 그 유형을 수동으로 정의할 수는 있겠지만, 그건 마치 나에게 반복하는 것처럼 들린다.그런 식으로 해서 지금은 수업을 연장하는 대신 기능을 하게 되었다(누군가 알면 다른 해결책을 알려주면 기쁠 것 같다.
import { Store } from 'vuex'
import VueRouter from 'vue-router'
// ...
export default (router: VueRouter) => {
return new Store({
// router = Vue.observable(router) // You can either do that...
super({
state: {
// router // ... or add `router` to `store` if You need it to be reactive.
// ...
},
// ...
})
}
import Vue from 'vue'
import App from './App.vue'
import createStore from './store'
// ...
new Vue({
router,
store: createStore(router),
render: createElement => createElement(App)
}).$mount('#app')
초기답변내용
난 그냥 평범한 사람을 위해 포장지를 만들었어Store
계급의
import { Store } from 'vuex'
import VueRouter from 'vue-router'
// ...
export default class extends Store<any> {
constructor (router: VueRouter) {
// router = Vue.observable(router) // You can either do that...
super({
state: {
// router // ... or add `router` to `store` if You need it to be reactive.
// ...
},
// ...
})
}
}
만약 당신이 필요하다면$route
그냥 사용해도 된다.router.currentRoute
그냥 기억해 넌 오히려 필요해router
원하는 경우 반응성getters
와 함께router.currentRoute
예상대로 일을 하다
그리고 "main.ts"(또는 ".js")에서는 그냥 같이 사용한다.new Store(router)
.
import Vue from 'vue'
import App from './App.vue'
import Store from './store'
// ...
new Vue({
router,
store: new Store(router),
render: createElement => createElement(App)
}).$mount('#app')
참조URL: https://stackoverflow.com/questions/40767874/how-to-use-vue-router-from-vuex-state
'programing' 카테고리의 다른 글
Vuex Getter가 업데이트되지 않음 (0) | 2022.05.02 |
---|---|
Light C 유니코드 라이브러리 (0) | 2022.05.02 |
bootstrap-vue: 특정 css 가져오기 (0) | 2022.05.02 |
C에서 열거형의 크기는 얼마인가? (0) | 2022.05.02 |
Vue js 호출 동작 내부 동작 (0) | 2022.05.02 |