1. 在根目录下新建store目录, 在store目录下创建index.js定义状态值import Vue from 'vue';
import Vuex from 'Vuex';
import Vuex from 'vuex';
Vue.use(Vuex);const store = new Vuex.Store({ state: { login: false, token: '', avatarUrl: '', userName: '' }, mutations: { login(state, provider) { console.log(state) console.log(provider) state.login = true; state.token = provider.token; state.userName = provider.userName; state.avatarUrl = provider.avatarUrl; }, logout(state) { state.login = false; state.token = ''; state.userName = ''; state.avatarUrl = ''; } }
})export default store2. 在main.js挂载Vueximport store from './store'
Vue.prototype.$store = store3. 在页面中使用
<script>import {mapState,mapMutations} from 'vuex';export default {computed: {...mapState(['avatarUrl','login','userName'])},methods: {...mapMutations(['logout'])}}
</script>在我实际开发项目中 使用如下