Table of Contents
具体步骤:
Home Web Front-end Vue.js How to use vuex in vue3+vite

How to use vuex in vue3+vite

Jun 03, 2023 am 09:10 AM
vue3 vite vuex

具体步骤:

1、安装vuex( vue3建议 4.0+ )

pnpm i vuex -S
Copy after login

2、main.js中配置

import store from '@/store'
// hx-app的全局配置
const app = createApp(App)
app.use(store)
Copy after login

3、新建相关的文件夹与文件,这里配置多个不同vuex内部的js,使用vuex的modules来放不同的页面,文件,然后统一使用一个getters.js

How to use vuex in vue3+vite

index.js 核心文件,这里使用了import.meta.glob,而不是require

import getters from './getters'
import { createStore } from 'vuex'
 
const modulesFiles = import.meta.glob('./modules/*.js',{ eager: true }); // 异步方式
 
let modules = {}
for (const [key, value] of Object.entries(modulesFiles)) {
  var moduleName = key.replace(/^\.\/(.*)\.\w+$/, '$1');
  const name = moduleName.split('/')[1]
  modules[name] = value.default
}
 
const store = createStore({
  modules,
  getters
})
 
export default store
Copy after login

getters.js 内部根据不同的页面来发送不同的state数据

const getters = {
  sidebar: state => state.app.sidebar,
  token: state => state.user.token,
}
 
export default getters
Copy after login

app.js 可以定义不同的变量,然后统一 export default

const state = {
  sidebar: '123'
}
 
const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar = '2222'
   
  },
 
const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  }
}
 
export default {
  namespaced: true,// 为每个模块添加一个前缀名,保证模块命明不冲突
  state,
  mutations,
  actions
}
Copy after login

user.js 也可以直接返回一个对象,写法都可以

export default {
  state: {
    token: '123'
  },
 
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
  },
 
  actions: {
  }
}
Copy after login

4、具体页面使用

1)引入

import { useStore } from 'vuex'
Copy after login

2)具体使用

setup(){
    const store = useStore()
}
Copy after login

How to use vuex in vue3+vite

3)使用 mutations里面的方法

store.commit("app/TOGGLE_SIDEBAR", 1)
Copy after login

4)使用actions里面的方法

store.dispatch("app/asyncAddStoreCount", 2)
Copy after login

5、vuex中推出了一个插件(vuex-persistedstate),可以解决刷新数据无保存的问题, 可以把数据除了vuex以外,在本地和会话(都支持)储存下

1)安装

pnpm i vuex-persistedstate -S
Copy after login

2)store/index.js

import createPersistedstate from 'vuex-persistedstate' //第一步导入
import { createStore } from 'vuex'
const store = createStore({
  modules,
  getters,
  //第二步是加这段代码,默认是存到了localStorage中
  plugins: [
    createPersistedstate({
      key: 'vuex-local', //存储持久状态的键。(默认:vuex)
      paths: ['user'], //部分持续状态的任何路径的数组。如果不加,默认所有。
      // storage: window.sessionStorage //默认存储到localStorage,想要存储到sessionStorage
    })
  ]
})
Copy after login

API

创建一个新的插件实例,使用提供的选项来生成持久化状态。可以提供以下选项来配置您的特定需求的插件:

  • key :存储持久状态的键。(默认:vuex)

  • paths :部分持续状态的任何路径的数组。如果没有路径给出,完整的状态是持久的。(默认:[])

  • reducer :一个函数,将被调用来基于给定的路径持久化的状态。默认包含这些值。

  • subscriber :一个被调用来设置突变订阅的函数。默认为store => handler => store.subscribe(handler)

  • storage :而不是(或与)getState和setState。默认为localStorage。

  • getState :将被调用以重新水化先前持久状态的函数。默认使用storage。

  • setState :将被调用来保持给定状态的函数。默认使用storage。

  • filter :将被调用来过滤将setState最终触发存储的任何突变的函数。默认为() => true

The above is the detailed content of How to use vuex in vue3+vite. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue3+TS+Vite development skills: how to optimize SEO Vue3+TS+Vite development skills: how to optimize SEO Sep 10, 2023 pm 07:33 PM

Vue3+TS+Vite development skills: How to perform SEO optimization SEO (SearchEngineOptimization) refers to optimizing the structure, content and keywords of the website to rank it higher in search engines, thereby increasing the website's traffic and exposure. . In the development of modern front-end technologies such as Vue3+TS+Vite, how to optimize SEO is a very important issue. This article will introduce some Vue3+TS+Vite development techniques and methods to help

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

Vue3+TS+Vite development skills: how to encrypt and store data Vue3+TS+Vite development skills: how to encrypt and store data Sep 10, 2023 pm 04:51 PM

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

Vue3+TS+Vite development skills: how to optimize cross-domain requests and network requests Vue3+TS+Vite development skills: how to optimize cross-domain requests and network requests Sep 09, 2023 pm 04:40 PM

Vue3+TS+Vite development skills: How to optimize cross-domain requests and network requests Introduction: In front-end development, network requests are a very common operation. How to optimize network requests to improve page loading speed and user experience is one of the issues that our developers need to think about. At the same time, for some scenarios that require sending requests to different domain names, we need to solve cross-domain issues. This article will introduce how to make cross-domain requests and optimization techniques for network requests in the Vue3+TS+Vite development environment. 1. Cross-domain request solution

Vue3+TS+Vite development skills: how to carry out front-end security protection Vue3+TS+Vite development skills: how to carry out front-end security protection Sep 09, 2023 pm 04:19 PM

Vue3+TS+Vite development skills: How to carry out front-end security protection. With the continuous development of front-end technology, more and more companies and individuals are beginning to use Vue3+TS+Vite for front-end development. However, the security risks that come with it have also attracted people's attention. In this article, we will discuss some common front-end security issues and share some tips on how to protect front-end security during the development process of Vue3+TS+Vite. Input validation User input is often one of the main sources of front-end security vulnerabilities. exist

How to use defineCustomElement to define components in Vue3 How to use defineCustomElement to define components in Vue3 May 28, 2023 am 11:29 AM

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

See all articles