Vue3中使用vuex4

目录

1、引入依赖:

2、新建文件夹 store ,在里面新建文件 index.js

3、index.js文件内容:

4、在 main.js 中引入

5、使用

6、修改 count 的值,这个和在 vue2 中的写法一样:

1、引入依赖:

npm i vuex

2、新建文件夹 store ,在里面新建文件 index.js

3、index.js文件内容:

import { createStore } from 'vuex'

export default createStore({
  state: { 
  
  },
  mutations: { 
     
  },
  actions: {  
    
  },
  modules: {
  }
})

4、在 main.js 中引入

import store from './store'

5、使用

在 store/index.js 的 state 中添加 count: 0

在任一组件文件中:加入下面代码:

import { useStore } from "vuex";
export default {
  name: "App",
  setup() {
    // Vue3 有个 composition api 的入口
    const store = useStore();// 获取容器
    
  },
};

获取到容器 store 后 ,获取 Vuex 中的 count 的值,通过 store.state.count 来获取。

 

直接在 template 中使用,目前可以使用旧版本写法

 如果想要字段 count 改变后,页面显示数据也改变,需要引入 vue 的计算属性 computed

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <h1>Vuex</h1>
  <h1>{{ count }}</h1>
</template>


<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
  name: "App",
  setup() {
    // Vue3 有个 composition api 的入口
    const store = useStore(); // 获取容器
    // 获取 Vuex 中的 count 的值
    console.log("store.state.count", store.state.count);
    return {
      count: computed(() => store.state.count),
    };
  },
};
</script>

6、修改 count 的值,这个和在 vue2 中的写法一样:

在 store/index.js 中添加下面代码:

 mutations: { 
    add(state, payload) {
      state.count += payload
    }
  },

在 要修改  count 的值的组件中通过 commit 来修改

store.commit('add', 3)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值