1:安装
npm install vuex --save
2: 在main.js 主入口js里面引用store.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store' //引用store.js
Vue.config.productionTip = false //阻止在启动时生成生产提示
//vue实例
new Vue({
el: '#app',
router,
store, //把store挂在到vue的实例下面
template: '<App/>',
components: { App }
})
3:在store.js里引用Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex) //注册Vuex
// 定义常量 如果访问他的话,就叫访问状态对象
const state = {
count: 1
}
// mutations用来改变store状态, 如果访问他的话,就叫访问触发状态
const mutations = {
//这里面的方法是用 this.$store.commit('jia') 来触发
jia(state){
state.count ++
},
jian(state){
state.count --
},
}
//暴露到外面,让其他地方的引用
export default new Vuex.Store({
state,
mutations
})
4:在vue组件中使用
使用$store.commit(‘jia’)区触发mutations下面的加减方法
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{$store.state.count}}</h5>
<p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</p>
</p>
</template>
<!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 -->
<style scoped>
h5{
font-size: 20px;
color: red;
}
</style>
5:state访问状态对象
使用computed计算
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{count}}</h5>
<p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</p>
</p>
</template>
<script>
import {mapState} from 'vuex'
export default{
name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
// 方法一
// computed: {
// count(){
// return this.$store.state.count + 6
// }
// }
// 方法二 需要引入外部 mapState
computed:mapState({
count:state => state.count + 10
})
// ECMA5用法
// computed:mapState({
// count:function(state){
// return state.count
// }
// })
//方法三
// computed: mapState([
// 'count'
// ])
}
</script>