定义简单store
var store = {
debug: true,
state: {
userInfo: null
},
loginInAction (userInfo) {
if (this.debug) console.log('loginInAction triggered with', JSON.stringify(userInfo))
this.state.userInfo = userInfo
TopHeader.$data.userInfo = userInfo
Profile.$data.userInfo = userInfo
},
loginOutAction() {
if (this.debug) console.log('loginOutAction triggered')
this.state.userInfo = null
TopHeader.$data.userInfo = null
Profile.$data.userInfo = null
}
}
定义两个实例
// TopHeader(用户操作)
var TopHeader = new Vue({
el: '#header',
data: function () {
return {
name: 'header',
userInfo: store.userInfo
}
},
methods: {
handleLogOut: function(){
store.loginOutAction();
},
handleLogIn: function(){
const userInfo = { name: 'Mr.L', avatar: 'http://f2.sjbly.cn/a14/0108/2124/1101mrk_180x180_m.jpg' }
store.loginInAction(userInfo);
}
},
template: `
<div class="header">
<div v-if="userInfo">
<a @click="handleLogOut">logout</a>
</div>
<div v-else>
<a @click="handleLogIn">login</a>
</div>
</div>
`
});
// Profile(用户简介)
var Profile = new Vue({
el: '#profile',
data: function () {
return {
name: 'profile',
userInfo: store.userInfo
}
},
template: `
<div class="profile">
<div v-if="userInfo">
<h3 class="name ">Welcome,{{ userInfo.name }}</h3>
<img class="avatar" :src="userInfo.avatar" />
</div>
</div>
`
});
完整代码:
github.com/pengjielee/…