1 基本介绍
Vuex是一个专为Vue.js应用程序开发的状态管理器。
2 应用场景
在多个组件里共享的状态,比如用户的登录状态,名称、头像、地理位置、购物车等。
3 安装方式
npm install vuex --save
4 代码部署
4.1 srcstoreindex.js
import Vue from "vue"; import Vuex from 'vuex' //1 安装插件 Vue.use(Vuex) //2 创建对象 //Vuex有一个Store类 const store = new Vuex.Store({ //保存状态 state:{ counter:999 }, mutations:{ //方法 默认带state参数 increment(state){ state.counter++ }, decrement(state){ state.counter-- } }, actions:{ }, getters:{ }, modules:{ } }) //3 导出store对象 export default store
4.2 srcmain.js
import Vue from 'vue' import App from './App.vue' import router from './router' import store from "./store"; Vue.config.productionTip = false new Vue({ router, store, render: function (h) { return h(App) } }).$mount('#app')
4.3 srcApp.vue
<template> <div id="app"> <h2>message:{{message}}</h2> <h5>counter:{{counter}}</h5> <h5>counter:{{$store.state.counter}}</h5> <h5>通过@click="counter++修改"</h5> <button @click="counter++">+</button> <button @click="counter--">-</button> <h5> 通过 @click="$store.state.counter++修改 官方不建议这样来改"</h5> <button @click="$store.state.counter++">+</button> <button @click="$store.state.counter--">-</button> <h5>通过mutations修改</h5> <button @click="addition">+</button> <button @click="subtraction">-</button> <!-- <router-view/>--> <hello-vuex></hello-vuex> </div> </template> <script> import HelloVuex from "./components/HelloVuex"; export default { name:'App', components:{ HelloVuex }, data(){ return { message:'我是app组件', counter:0 } }, methods:{ addition(){ this.$store.commit('increment') }, subtraction(){ this.$store.commit('decrement') } } } </script> <style> </style>
安装Devtools插件
代码下载
链接:https://pan.baidu.com/s/1rax0wgZg895GmvQ5ryZTJQ
提取码:fcz3