一、新建项目
在webstorm中输入指令:npm create 项目名称
二、安装Vuex
进入新建好的项目中,输入指令:npm install vuex --save
三、简单使用
在项目的src目录下新建一个store文件夹,在store目录下新疆一个index.js文件:
在index.js文件中导入Vue和Vuex
import Vue from 'vue'
import Vuex from 'vuex'
通过Vue的use(插件)使用Vuex插件
Vue.use(Vuex)
创建Vuex对象,在state状态中定义一个count变量和两个方法(一个加,一个减)
const store =new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
state.count++;
},
sub(state){
state.count--;
}
}
})
导出Vuex对象至main.js
export default store
进入main.js,导入store(Vuex对象)
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// 导入Vuex对象
import store from './store/index'
new Vue({
store,
render: h => h(App),
}).$mount('#app')
下一步就是到App.vue中把store中的count显示出来,并可以进行加减操作
<template>
<div id="app">
<h1>展示vuex中管理的状态</h1>
<h1>{{$store.state.count}}</h1>
<button @click="add()">+</button>
<button @click="sub()">-</button>
<HelloWorld></HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
methods:{
add(){
this.$store.commit('add')
},
sub(){
this.$store.commit('sub')
}
}
}
</script>
<style>
</style>
接下来到Helloworld.vue中进行一样的操作
<template>
<div class="hello">
<hr/>
<h1>{{$store.state.count}}</h1>
<button @click="add()">+</button>
<button @click="sub()">-</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
methods:{
add(){
this.$store.commit('add')
},
sub(){
this.$store.commit('sub')
}
}
}
</script>
<style scoped>
</style>
总结
通过State状态管理数据,其他组件可以将数据并显示出来(View),如果要对数据进行更改,则要通过Actions也就是事件来对state中的数据进行操作。