Vue官方文档(48): vuex的基本使用

1.在package.json中增加vuex

"vuex": "^3.6.2"

2.运行npm install
3.在src目录下新建store目录,在store目录中创建文件store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
export default store;

4.在需要的页面引入store,并使用

//路径
import store from './store/store'
  store.commit('increment');
  alert(store.state.count);

也可以在根实例中引入上述store. 修改main.js
1)

import store from './store/store'

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

3)之后就可以全局使用store了

          alert(this.$store.state.count);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中使用Vuex,你需要按照以下步骤进行设置: 1. 安装Vuex:在终端中运行以下命令安装Vuex: ``` npm install vuex@next ``` 2. 创建一个Vuex store:在你的项目中创建一个新的文件(例如store.js),并导入`createStore`函数和你的模块文件(如果有的话): ```javascript import { createStore } from 'vuex'; import moduleA from './moduleA'; export default createStore({ modules: { moduleA } }); ``` 3. 创建模块(可选):如果你的应用程序需要使用模块来组织状态,你可以创建一个或多个模块文件。在上面的示例中,我们导入了一个名为moduleA的模块。 4. 在Vue应用程序中使用Vuex:在你的main.js文件中导入创建的store,并将其与Vue应用程序实例关联: ```javascript import { createApp } from 'vue'; import App from './App.vue'; import store from './store'; const app = createApp(App); app.use(store); app.mount('#app'); ``` 现在,你可以在你的Vue组件中使用Vuex的功能,包括状态管理、mutations、actions和getters等。 例如,在组件中访问和修改状态: ```javascript import { useStore } from 'vuex'; export default { setup() { const store = useStore(); // 访问状态 const count = computed(() => store.state.moduleA.count); // 修改状态 const increment = () => { store.commit('moduleA/increment'); }; return { count, increment }; } }; ``` 这就是在Vue 3中使用Vuex基本步骤。你可以在官方文档中了解更多关于Vuex的信息:https://next.vuex.vuejs.org/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值