vuex中的store存储数据

本文介绍了如何在Next.js项目中安装并使用Vuex。首先,通过npm或yarn引入Vuex并配置store。然后展示如何在store中创建state、getters、mutations和actions。最后,讲解了如何在组件中监听state变化以及提交数据到state。
摘要由CSDN通过智能技术生成
1、安装

npm install vuex@next --save

yarn add vuex@next --save

 2、搭建store

        在vue项目main.js中挂载

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from "@/store/deviceProps";


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

        在 src 目录下新建 store 文件夹,在 store 文件夹内新建一个deviceProps.js文件

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    //类似于vue中的data,是唯一数据源,是一个对象
    state: {
        data: {
            powerstate: 0,
        }
    },
    // 和vue中的计算属性类似,state中的数据发生变化时,它就会触发
    // 并且会自动保存修改了的内容
    getters:{
        getData(state) {
            return state.data
        }
    },
    // 更改state中状态的逻辑,主要是写一些同步操作的方法
    mutations: {
        addData(state, person) {
            state.data = {
                ...state.data,
                ...person,
            }
        }
    },
    // 提交mutation,区别在于可以异步操作
    actions:{},
    // 将store分割成模块
    modules:{}
})
export default store

3、在组件中获取state

export default {
        name: "test_1",
        data() {
            return {
                a: {}
            }
        },
        watch: {
            '$store.state.data': {
                deep: true,//对象需深度监听
                handler: function (newVal) {
                    this.a = newVal;
                }
            }
        },

        mounted() {
            this.a = this.$store.getters.getData // 通过getters访问
        }
}

4、页面中提交数据给state

使用commit()可将deviceProps数据传递给addData
this.$store.commit('addData', this.deviceProps);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值