1、在项目目录下安装vuex
npm install vuex --save
2、在src目录下新建一个store目录,在store目录下新建index.js文件
index.js代码如下:
import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name: '蔡毛毛'
}
})
在主入口文件引入vuex
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import store from './store/index.js' //引入store
import 'element-ui/lib/theme-chalk/index.css'// 默认主题
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //store挂载到vue实例
components: { App },
template: '<App/>'
})
组件使用store
<div>
{{this.$store.state.name}}
</div>
*
*
*
*
*
二、怎么改变store里state存放的值
比如我点击一个按钮改变name的值
<button @click="handleNameClick(name)"></button>
<script>
export default{
methods:{
handleNameClick (name) {
this.$store.dispatch('changeName',name)
}
}
}
</script>
store派发了一个changeName的action
所以需要在store中添加一个action为changeName的事件
这部分理解起来可能会有点难,是时候上下图了
三、vuex高级api
import {mapState} from 'vuex'
export default{
computed: {
...mapState(['name'])
}
import {mapMutations} from 'vuex';
...mapMutations(['changeName')
组件调用时就可以this.changeName这样用了。。this.$store.commit可以被替换掉
(完)