vuex的基本使用--vuex入门

在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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值