Vue3中vuex的基本使用方法实例

您所在的位置:网站首页 vuex的使用举例 Vue3中vuex的基本使用方法实例

Vue3中vuex的基本使用方法实例

2022-06-03 15:33| 来源: 网络整理| 查看: 265

Vue3中vuex的基本使用方法实例,方法,数据,实例,定义,对象

Vue3中vuex的基本使用方法实例

易采站长站,站长之家为您整理了Vue3中vuex的基本使用方法实例的相关内容。

目录一、基本结构二、基本使用三、将store中的数据模块化后的使用1.模块化2.使用补充:如何改变vuex中的属性总结 

一、基本结构

src/store/index.js中,代码如下

// vue3中创建store实例对象的方法createStore()按需引入import { createStore } from 'vuex'export default createStore({ state: { }, mutations: { }, actions: { }, getters: { }, modules: { }})

二、基本使用

src/store/index.js

import { createStore } from 'vuex'export default createStore({ state: { info: 'hello' }, mutations: { // 定义mutations,用于修改状态(同步) updateInfo (state, payload) { state.info = payload } }, actions: { // 定义actions,用于修改状态(异步) // 2秒后更新状态 updateInfo (context, payload) { setTimeout(() => { context.commit('updateInfo', payload) }, 2000) } }, getters: { // 定义一个getters formatInfo (state) { return state.info + ' Tom' } }, modules: { }})

src/views/Test.vue测试组件中对store中数据的操作与使用

测试组件 获取Store中的state、getters: {{$store.getters.formatInfo}} 点击// 按需引入useStore()方法import { useStore } from 'vuex'export default { name: 'Test', setup () { // this.$s易采站长站tore.state.info // Vue3中store类似于Vue2中this.$store // useStore()方法创建store对象,相当于src/store/index.js中的store实例对象 const store = useStore() console.log(store.state.info) // hello // 修改info的值 const handleClick = () => { // 触发mutations,用于同步修改state的信息 // store.commit('updateInfo', 'nihao') // 触发actions,用于异步修改state的信息 store.dispatch('updateInfo', 'hi') } return { handleClick } }}

点击按钮前

pdateNickname', 'Yee') } return { handleClick } }}

点击按钮前

Vue3中vuex的基本使用方法实例

点击按钮后

Vue3中vuex的基本使用方法实例

补充:如何改变vuex中的属性

vue3和vue2一样,都是通过提交mutations中的方法,进行对vuex中数据的改变,那具体该如何使用呢?首先看一下mutations中的写法

const mutations = { addCount(state, payload) { state.count += payload },}export { mutations }

这里,定义了一个addCount方法,这个方法接受两个参数,第一个参数是要改变的state对象(当然你调用这个放法的传参中也可以写state.count,然后再mutations中直接state += payload就可以了),第二个参数是要改变的数据,比如进行 +1 操作

vuex中的数据{{ store.state.count }} 改变vuex数据import { defineComponent } from "vue"import { useStore } from "vuex"export default defineComponent({ name: "index", setup() { const store = useStore() console.log(store) const changeStoreCount = () => { // 在这里提交了mutations中的addCount方法 store.commit("addCount", 1) } return { store, changeStoreCount } },})

总结 以上就是关于对Vue3中vuex的基本使用方法实例的详细介绍。欢迎大家对Vue3中vuex的基本使用方法实例内容提出宝贵意见



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3