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)

猜你喜欢

转载自blog.csdn.net/A88552211/article/details/125310043