什么是vuex状态管理?
就是我们vue里的核心数据库
- 安装
$ npm install vuex --save
- 在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 }
})
- 在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
})
- 在vue组件中使用
使用$store.commit(‘jia’)区触发mutations下面的加减方法
<template>
<div 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>
</div>
</template>
<!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 -->
<style scoped>
h5{
font-size: 20px;
color: red;
}
</style>