在src下新建store文件夹,在store新建index.js,在main.js中导入store,挂载store,注册了一个组件hellovuex
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state:{
count:1000,
students:[
{id:110,name:'aa',age:18},
{id:111,name:'bb',age:22},
{id:112,name:'cc',age:20},
{id:113,name:'dd',age:25},
],
info:{
"name":"hhh",
"age":18,
"height":1.88
}
},
mutations: {
//方法 //不能进行异步操作
increment(state) {//默认传过来一个参数 state
state.count ++
},
decrement(state) {
state.count --
},
updateinfo(state){
state.info.name = "wubna"
}
},
actions:{
//action类似于mutation,但是是用来代替mutation进行异步操作的
aupdateinfo(context){
context.commit('updateinfo')
}
},
getters: {
// 可以认为是 store 的计算属性
more20stu(state) {
return state.students.filter(s => {
return s.age>20
})
}
}
});
export default store
app.vue
<template>
<div id="app">
<h2>{{ $store.state.count }}</h2>
<h2>{{ $store.state.info}}</h2>
<!-- <h2>{{ $store.state.students}}</h2> -->
<h2>{{ $store.getters.more20stu}}</h2>
<h1>hellovuex的内容</h1>
<button @click="add">+</button>
<button @click="sub">-</button>
<button @click="updateinfo">修改名字</button>
<hellovuex></hellovuex>
</div>
</template>
<script>
import hellovuex from './components/hellovuex'
export default {
name: 'App',
components: {
hellovuex
},
methods: {
add(){
this.$store.commit('increment')
},
sub(){
this.$store.commit('decrement')
},
updateinfo(){
this.$store.dispatch('aupdateinfo')
},
more20stu(){
}
}
}
</script>
<style>
</style>
hellovuex.vue
<template>
<div>
<h2>{{ $store.state.count }}</h2>
<h2>{{ $store.state.students}}</h2>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
</style>