mud*_*din 9 javascript vue.js vuex
有User.js类和用户对象(user = new User();).
该user对象正在所有嵌套组件中使用.在User课堂上有很多重要的方法.
如何在任何组件中简单地使用/ access this.user或其this.$user方法?
1解决方案(临时工作解决方案):user在vuex商店中设置并在所有组件中定义'data:
data(){
return {
user:this.$store.state.user
}
}
Run Code Online (Sandbox Code Playgroud)
缺点:在每个组件中,都应该添加.注意:组件太多了.
2解决方案:将用户添加到Vue的原型中,如插件:
Vue.prototype.$user = user
Run Code Online (Sandbox Code Playgroud)
缺点:当user数据发生变化时,它不会影响 DOM元素(UI).
3解决方案:放置组件的道具.
缺点:在每个组件中,都应该添加.注意:同样有很多组件.
我发现的所有解决方案都存在问题,特别是随着项目变得越来越大.
任何建议和解决方案将不胜感激!
getterswith mapGettersfrom Vuex 将用户包含在每个组件的计算属性中。Vuex
getters: {
// ...
getUser: (state, getters) => {
return getters.user
}
}
Run Code Online (Sandbox Code Playgroud)
成分
import { mapGetters } from 'vuex'
computed: {
...mapGetters([getUser])
}
Run Code Online (Sandbox Code Playgroud)
视图
// 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)
Run Code Online (Sandbox Code Playgroud)
用户观察者插件.js
const UserPlug = {
install(Vue, options) {
// We call Vue.mixin() here to inject functionality into all components.
Vue.watch: 'user'
}
};
export default UserPlug;
Run Code Online (Sandbox Code Playgroud)
user通过 mixin添加一个计算属性作为插件视图
// 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)
Run Code Online (Sandbox Code Playgroud)
用户观察者插件.js
const UserPlug = {
install(Vue, options) {
// We call Vue.mixin() here to inject functionality into all components.
Vue.mixin({
computed: {
user: function() {
return this.$store.state.user
}
}
})
}
};
export default UserPlug;
Run Code Online (Sandbox Code Playgroud)