Vue3 coderwhy24-25p Vuex状态管理

260 阅读1分钟

Vuex的基本使用

  • 安装
- npm install vuex@next
  • 创建文件夹store -> index.js
- import { createStore } from "vuex";
- 
- //调用函數創建仓库
- const store = createStore({
-   state() {
-     return {
-       realman: '阿伦',
-     };
-   },
- });
- 
- export default store;
  • 组件中展示调用
- $store.state.xxx
  • 组件中操作
- (1) 组件中定义一个方法,commit提交mutation方法
    - changeMan(){
    -     this.$store.commit("changeMan")
    -   }

- (2) index.js里定义mutation
>     - mutations:{
>     -     changeMan(state){
>     -       state.realman = "小叮当"
>     -     }
>     -   }

Vuex的state在组建中的computed写法

- import { mapState } from "vuex";
- 
- export default {//数组写法
-   computed:{
-     fullname(){
-       return "大叮当"+"哆啦A梦"
-     },
-     //解构语法,其他从state获取的计算属性
-     ...mapState(["realman","age","name","sex"])
-   },
- }

-  //第二种对象写法
-     ...mapState({//可以重新定义名字
-       sname: state => state.name,
-       sage: state => state.age,
-     })

getters的基本使用

  • 在store的index.js
- state() {
-     return {
-       bookPrice: 50,
-       penPrice: 20,
-     };
-   },
- getters:{
-     totalPrice(state,getters){//两个参数
-       let totalPrice = state.bookPrice + getters.penPrcie;
-       return totalPrice
-     },
-     penPrcie(state){
-       return state.penPrice + 10;
-     }
-   }
  • 组件页面
-   总价值:{{ $store.getters.totalPrice }}
  • getters里的方法可以return方法定义参数,在页面输入参数去调用

getters的computed写法

- import { mapState,mapGetters } from "vuex";
- //getters获取的值
-     ...mapGetters(['a','b']),//数组写法
-     ...mapGetters({
-       cc: "a",
-       dd: "b"
-     })