安装包
npm install vuex@next --save
在main.js入口文件引入store文件并绑定在vue实例上
import store from './store'
app.use(store)
创建一个store文件夹,并创建一个index.js文件
引入createstore方法使用它创建store
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
count: 10
}
},
mutations: {
increment(state) {
state.count += 1
}
},
actions: {
asyncIncrement(store) {
store.commit('increment');
// 调用接口
// async test(){
// await axios
// await store.commit('')
// }
}
}
})
export default store
组件里调用
点击触发事件commit分发一个action给matations
通过computed把store的状态更新到视图中
通过dispatch分发action到actions里
<template>
<div>
<h1>tow1组件</h1>
<button @click="btnadd">+</button>
<h2>store的状态为{{ count }}</h2>
<router-link to="/tow2">tow2页面</router-link>
</div>
</template>
<script>
export default {
data() {
return {
}
},
mounted() {
console.log(this.$store.state.count)
},
// state.getser获取二次修改的状态
// computed同步更新store里的状态到视图
computed: {
count() {
return this.$store.state.count
}
},
methods:{
btnadd(){
// this.$store.commit('increment')
// 触发异步
this.$store.dispatch('asyncIncrement')
}
}
}
</script>