注:适用于Vue 2x
建议1:使用vuex的getter
- You could use
getters
along with mapGetters
from Vuex to include users within computed properties for each 组成部分.
Vuex
getters: {
// ...
getUser: (state, getters) => {
return getters.user
}
}
组成部分
import { mapGetters } from 'vuex'
computed: {
...mapGetters([getUser])
}
建议2:通过插件添加观察者
Vue
// When using CommonJS via Browserify or Webpack
const Vue = require('vue')
const UserPlug = require('./user-watcher-plugin')
// Don't forget to call this
Vue.use(UserPlug)
用户观察插件.js
const UserPlug = {
install(Vue, options) {
// We call Vue.mixin() here to inject functionality into all 组成部分s.
Vue.watch: 'user'
}
};
export default UserPlug;
Proposal 3: add a computed property user
as plugin via mixin
Vue
// When using CommonJS via Browserify or Webpack
const Vue = require('vue')
const UserPlug = require('./user-watcher-plugin')
// Don't forget to call this
Vue.use(UserPlug)
用户观察插件.js
const UserPlug = {
install(Vue, options) {
// We call Vue.mixin() here to inject functionality into all 组成部分s.
Vue.mixin({
computed: {
user: function() {
return this.$store.state.user
}
}
})
}
};
export default UserPlug;