我有一个单页应用程序,其中包含:
包含标题和菜单的导航组件 路由器 View 我希望在路由器 View 中呈现与路由器中的状态相对应的每个组件,以更新导航组件的标题。如何将参数从路由器 View 中的组件传递到外部导航组件。
我使用的是vue 2.0
最佳答案
为此我会推荐 Vuex:
这样你就可以在主组件中访问你的 Vuex 存储并显示它的标题:
computed: {
title () {
return this.$store.state.title
}
}
然后,您可以设置一个突变来更新标题,并在组件中需要的地方调用它。现在,由于 Vue 是响应式(Reactive)的,导航组件中的标题将会更新。
下面是一个简短的示例:
Vuex 商店:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
title: ''
},
mutations: {
updateTitle (state, title) {
state.title = title
}
}
})
您的应用程序根目录:
import Vue from 'vue'
import store from './vuex/store'
new Vue({
el: '#app',
store,
})
导航组件:
export default {
computed: {
title () {
return this.$store.state.title
}
},
...
需要更新您的标题的任何其他组件:
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'updateTitle' // map this.updateTitle() to this.$store.commit('updateTitle')
]),
},
// if you wanted to call it on mount
mounted () {
this.updateTitle('hello')
},
...
关于vue.js - routerview中的 Controller 和父级 Controller 之间的两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709370/