vuex 学习笔记

store文件

import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)

let store = new Vuex.Store({
    state: {
        numbers: 0
    },
    // 只有 mutations 中定义的函数,才有权力修改 state 中的数据
    mutations: {
    // 改变化state中的值
        add(state){
            state.numbers ++
        },
        addN(state,step){
            state.numbers += step
        }

    },
    actions: {
        // 执行异步操作 用 commit 调用 mutations 中的 add 方法
        addAsync(context,step){
            context.commit('addN',step)
        }
    },
    modules: {}
})

export default store

man.js 全局注册


// 挂载store
import store from "@/store";

new Vue({
    store,
    router, render: h => h(App)
}).$mount('#app');

组件中引用  store

created() {
console.log(this.$store.state.numbers)
},
methods:{
    handle(){
// commit 的作用是 调佣某个 mutation 函数
        this.$store.commit('add')
// 这里的 dispatch 函数,专门用来触发 actions 函数
        this.$store.dispatch('addAsync',6)
    },
    handleN(){
// commit 的作用是 调佣某个 mutation 函数
        this.$store.commit('addN',3)
    }
}

getter 使用

用于对 store 中的数据进行加工处理形成新的数据;

  • getter 可以对 store 中已有的数据加工处理之后形成新的数据,类似 vue 的计算属性
  • store 中数据发生变化,getter 的数据也会跟着变化

定义:

// 定义 getter 
const store = new Vuex.Store({
    state:{
        count:0
    },
    getters:{
        showNum(state){
            return '当前最新的数量是 [ '+ state.count +' ]'
        }
    }
})

使用方法:

<h3>{{$store.getters.showNum}}</h3>

vuex 使用案例

 store 方法

state: {
    list: []
},
mutations: {
    initList(state, list) {
      state.list = list
    }
},

actions: {
    getList(context) {
      axios.get('./newJson.json').then(res => {
        context.commit('initList',res.data)
      })
    }
}

组件使用

<template>
    <ul>
      <li v-for='(item,index) in list' :key='index'><i>{{ item.id }}</i>{{ item.title }}</li>
    </ul>

</template>


<script>
  computed: {
    // 将 store 中 list 数据映射出来,页面直接调用就行
    ...mapState(['list'])
  },
  created() {
    this.$store.dispatch('getList')
  }

</script>

 json 数据  (newJson.json)

[
  {
    "id": 0,
    "title": "你好"
  },
  {
    "id": 1,
    "title": "你好1"
  }
]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马卫斌 前端工程师

你的鼓励是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值