首页 > 其他分享 >【vuex小试牛刀】

【vuex小试牛刀】

时间:2024-06-05 15:00:10浏览次数:7  
标签:show js state dialog vuex 小试牛刀 store

了解vuex核心概念请移步 https://vuex.vuejs.org/zh/

img

# 一、初始vuex

# 1.1 vuex是什么

  •        
           

    就是把需要共享的变量全部存储在一个对象里面,然后将这个对象放在顶层组件中供其他组件使用

    • 父子组件通信时,我们通常会采用 props + emit 这种方式。但当通信双方不是父子组件甚至压根不存在相关联系,或者一个状态需要共享给多个组件时,就会非常麻烦,数据也会相当难维护

# 1.2 vuex中有什么

const store = new Vuex.Store({
    state: {
        name: 'weish',
        age: 22
    },
    getters: {
        personInfo(state) {
            return `My name is ${state.name}, I am ${state.age}`;
        }
    }
    mutations: {
        SET_AGE(state, age) {
            commit(age, age);
        }
    },
    actions: {
        nameAsyn({commit}) {
            setTimeout(() => {
                commit('SET_AGE', 18);
            }, 1000);
        }
    },
    modules: {
        a: modulesA
    }
}

    
    
     
     
      
       
      
      
     
      
     
     
    
    

这个就是最基本也是完整的vuex代码;vuex 包含有五个基本的对象

  • state:存储状态。也就是变量;
  • getters:派生状态。也就是setget中的get,有两个可选参数:stategetters分别可以获取state中的变量和其他的getters。外部调用方式:store.getters.personInfo()。就和vuecomputed差不多;
  • mutations:提交状态修改。也就是setget中的set,这是vuex中唯一修改state的方式,但不支持异步操作。第一个参数默认是state。外部调用方式:store.commit('SET_AGE', 18)。和vue中的methods类似。
  • actions:和mutations类似。不过actions支持异步操作。第一个参数默认是和store具有相同参数属性的对象。外部调用方式:store.dispatch('nameAsyn')
  • modulesstore的子模块,内容就相当于是store的一个实例。调用方式和前面介绍的相似,只是要加上当前子模块名,如:store.a.getters.xxx()

# 1.3 vue-cli中使用vuex的方式

目录结构

├── index.html
├── main.js
├── components
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── state.js          # 跟级别的 state
    ├── getters.js        # 跟级别的 getter
    ├── mutation-types.js # 根级别的mutations名称(官方推荐mutions方法名使用大写)
    ├── mutations.js      # 根级别的 mutation
    ├── actions.js        # 根级别的 action
    └── modules
        ├── m1.js         # 模块1
        └── m2.js         # 模块2

    
    
     
     
      
       
      
      
     
      
     
     

    
    

state示例

const state = {
    name: 'weish',
    age: 22
};
export default state;

    
    
     
     
      
       
      
      
     
      
     
     

    
    

getter示例

getters.js示例(我们一般使用getters来获取state的状态,而不是直接使用state

export const name = (state) => {
    return state.name;
}
export const age = (state) => {
    return state.age
}
export const other = (state) => {
    return `My name is ${state.name}, I am ${state.age}.`;
}

    
    
     
     
      
       
      
      
     
      
     
     

    
    

mutation-type示例

将所有mutations的函数名放在这个文件里

export const SET_NAME = ‘SET_NAME’;
export const SET_AGE = ‘SET_AGE’;

mutations示例

import * as types from ‘./mutation-type.js’;
export default {
[types.SET_NAME](state, name) {
state.name = name;
},
[types.SET_AGE](state, age) {
state.age = age;
}
};

actions示例

异步操作、多个commit

import * as types from ‘./mutation-type.js’;
export default {
nameAsyn({commit}, {age, name}) {
commit(types.SET_NAME, name);
commit(types.SET_AGE, age);
}
}

modules–m1.js示例

如果不是很复杂的应用,一般来讲是不会分模块的

export default {
state: {},
getters: {},
mutations: {},
actions: {}
}

index.js示例(组装vuex)

import vue from ‘vue’;
import vuex from ‘vuex’;
import state from ‘./state.js’;
import * as getters from ‘./getters.js’;
import mutations from ‘./mutations.js’;
import actions from ‘./actions.js’;
import m1 from ‘./modules/m1.js’;
import m2 from ‘./modules/m2.js’;
import createLogger from ‘vuex/dist/logger’; // 修改日志
vue.use(vuex);
const debug = process.env.NODE_ENV !== ‘production’; // 开发环境中为true,否则为false
export default new vuex.Store({
state,
getters,
mutations,
actions,
modules: {
m1,
m2
},
plugins: debug ? [createLogger()] : [] // 开发环境下显示vuex的状态修改
});

最后将store实例挂载到main.js里面的vue上去就行了

import store from ‘./store/index.js’;
new Vue({
el: ‘#app’,
store,
render: h => h(App)
});

vue组件中使用时,我们通常会使用mapGettersmapActionsmapMutations,然后就可以按照vue调用methodscomputed的方式去调用这些变量或函数,示例如

import {mapGetters, mapMutations, mapActions} from ‘vuex’;
/* 只写组件中的script部分 */
export default {
computed: {
…mapGetters([
name,
age
])
},
methods: {
…mapMutations({
setName: ‘SET_NAME’,
setAge: ‘SET_AGE’
}),
…mapActions([
nameAsyn
])
}
};

# 二、modules

在 src 目录下 , 新建一个 store 文件夹 , 然后在里面新建一个 index.js

import Vue from ‘vue’
import vuex from ‘vuex’
Vue.use(vuex);
export default new vuex.Store({
state:{
show:false
}
})

main.js 里的代码应该改成,在实例化 Vue对象时加入 store 对象

//vuex
import store from ‘./store’
new Vue({
el: ‘#app’,
router,
store,//使用store
template: ‘<App/>’,
components: { App }
})

这样就把 store 分离出去了 , 那么还有一个问题是 : 这里 $store.state.show 无论哪个组件都可以使用 , 那组件多了之后 , 状态也多了 , 这么多状态都堆在 store 文件夹下的 index.js 不好维护怎么办 ?

  • 我们可以使用 vuexmodules , 把 store 文件夹下的 index.js 改成
import Vue from ‘vue’
import vuex from ‘vuex’
Vue.use(vuex);
import dialog_store from ‘…/components/dialog_store.js’;//引入某个store对象
export default new vuex.Store({
modules: {
dialog: dialog_store
}
})

这里我们引用了一个 dialog_store.js , 在这个 js文件里我们就可以单独写 dialog 组件的状态了

export default {
state:{
show:false
}
}

做出这样的修改之后 , 我们将之前我们使用的 s t o r e . s t a t e . s h o w < / c o d e > 统统改为 < c o d e > store.state.show</code> 统统改为 <code> store.state.show</code>统统改为<code>store.state.dialog.show 即可

  • 如果还有其他的组件需要使用 vuex , 就新建一个对应的状态文件 , 然后将他们加入 store文件夹下的 index.js文件中的 modules
modules: {
dialog: dialog_store,
other: other,//其他组件
}

# 三、mutations

vuex 的依赖仅仅只有一个 $store.state.dialog.show 一个状态 , 但是如果我们要进行一个操作 , 需要依赖很多很多个状态 , 那管理起来又麻烦了

  • mutations里的操作必须是同步的
export default {
    state:{//state
        show:false
    },
    mutations:{
        switch_dialog(state){//这里的state对应着上面这个state
            state.show = state.show?false:true;
            //你还可以在这里执行其他的操作改变state
        }
    }
}

  
  
   
   
    
     
    
    
   
    
   
   

  
  

使用 mutations 后 , 原先我们的父组件可以改为

<template>
  <div id="app">
    <a href="javascript:;" @click="$store.commit('switch_dialog')">点击</a>
    <t-dialog></t-dialog>
  </div>
</template>
<script>
import dialog from './components/dialog.vue'
export default {
  components:{
    "t-dialog":dialog
  }
}
</script>

  
  
   
   
    
     
    
    
   
    
   
   
 
  
  

使用 $store.commit('switch_dialog') 来触发 mutations 中的 switch_dialog 方法

# 四、actions

多个 state 的操作 , 使用 mutations会来触发会比较好维护 , 那么需要执行多个 mutations 就需要用 action

export default {
    state:{//state
        show:false
    },
    mutations:{
        switch_dialog(state){//这里的state对应着上面这个state
            state.show = state.show?false:true;
            //你还可以在这里执行其他的操作改变state
        }
    },
    actions:{
        switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法
            context.commit('switch_dialog');
            //你还可以在这里触发其他的mutations方法
        },
    }
}

  
  
   
   
    
     
    
    
   
    
   
   

  
  

那么 , 在之前的父组件中 , 我们需要做修改 , 来触发 action 里的 switch_dialog 方法

<template>
  <div id="app">
    <a href="javascript:;" @click="$store.dispatch('switch_dialog')">点击</a>
    <t-dialog></t-dialog>
  </div>
</template>
<script>
import dialog from './components/dialog.vue'
export default {
  components:{
    "t-dialog":dialog
  }
}
</script>

  
  
   
   
    
     
    
    
   
    
   
   
  
  
  
  • 使用 $store.dispatch('switch_dialog') 来触发 action 中的 switch_dialog 方法。
  • 官方推荐 , 将异步操作放在 action

# 五、getters

gettersvue 中的computed 类似 , 都是用来计算 state 然后生成新的数据 ( 状态 ) 的

  • 假如我们需要一个与状态 show 刚好相反的状态 , 使用 vue 中的 computed 可以这样算出来
computed(){
    not_show(){
        return !this.$store.state.dialog.show;
    }
}

  
  
   
   
    
     
    
    
   
    
   
   

  
  

那么 , 如果很多很多个组件中都需要用到这个与 show刚好相反的状态 , 那么我们需要写很多很多个 not_show, 使用 getters就可以解决这种问题

export default {
    state:{//state
        show:false
    },
    getters:{
        not_show(state){//这里的state对应着上面这个state
            return !state.show;
        }
    },
    mutations:{
        switch_dialog(state){//这里的state对应着上面这个state
            state.show = state.show?false:true;
            //你还可以在这里执行其他的操作改变state
        }
    },
    actions:{
        switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法
            context.commit('switch_dialog');
            //你还可以在这里触发其他的mutations方法
        },
    }
}

  
  
   
   
    
     
    
    
   
    
   
   
 
  
  

我们在组件中使用 $store.state.dialog.show 来获得状态 show , 类似的 , 我们可以使用 $store.getters.not_show 来获得状态 not_show

  • 注意 : $store.getters.not_show 的值是不能直接修改的 , 需要对应的 state 发生变化才能修改

# 六、mapState、mapGetters、mapActions

很多时候 , $store.state.dialog.show$store.dispatch('switch_dialog') 这种写法很不方便

  • 使用 mapStatemapGettersmapActions 就不会这么复杂了
<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>
<script>
import {mapState} from 'vuex';
export default {
  computed:{
    //这里的三点叫做 : 扩展运算符
    ...mapState({
      show:state=>state.dialog.show
    }),
  }
}
</script>

  
  
   
   
    
     
    
    
   
    
   
   
 
  
  

相当于

<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>
<script>
import {mapState} from 'vuex';
export default {
  computed:{
    show(){
        return this.$store.state.dialog.show;
    }
  }
}
</script>

  
  
   
   
    
     
    
    
   
    
   
   
 
  
  

mapGettersmapActionsmapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods

标签:show,js,state,dialog,vuex,小试牛刀,store
From: https://blog.csdn.net/demotang1/article/details/139472289

相关文章

  • 【前端每日基础】day42——关于 Vuex 共有几个属性,哪里可以书写同步任务,哪里可以书写
    Vuex是Vue.js的一个状态管理模式,它集中式地存储和管理应用的所有组件的状态。Vuex提供了以下几个核心属性,每个属性在状态管理中有不同的用途:Vuex共有的几个属性:State:用于存储应用的状态。可以通过this.$store.state或在组件中通过mapState辅助函数访问。Gette......
  • vue之vuex使用
    如图所示,它是一个程序里面的状态管理模式,它是集中式存储所有组件的状态的小仓库,并且保持我们存储的状态以一种可以预测的方式发生变化。对于可以预测,现在我不多做说明,相信在看完这篇文章之后,你就会有自己的理解。第一步,了解Vuex......
  • vue2组件中监听vuex中state的值
    vue2组件中监听Vuex 中state的值可以使用 mapState。官网链接:mapGetters辅助函数仅仅是将store中的getter映射到局部计算属性。Getter|Vuex(vuejs.org)参考文档: 监听Vuex中的数据变化-资深if-else侠-博客园(cnblogs.com)Vuex入门(2)——state,mapState,...ma......
  • Vue搭建移动端h5项目(已开源,附带git地址)Vant+Vue Router+Vuex+axios封装+案例交互+部分
    一、项目介绍以及项目地址             项目介绍:vue2搭建。项目通过amfe-flexible与postcss-pxtorem实现移动端适配;通过Vantui作为项目的组件库;通过Vuex管理数据状态,进行模块化管理;通过VueRouter配置项目路由,进行模块化管理;封装axios进行数据的请求,以及一些页......
  • Vuex
    【一】了解Vuex【1】想象一个场景如果你的项目里有很多页面(组件/视图),页面之间存在多级的嵌套关系,此时,这些页面假如都需要共享一个状态的时候,此时就会产生以下两个问题:多个视图依赖同一个状态来自不同视图的行为需要变更同一个状态【2】解决方案​ 对于第一个问题,假如是多......
  • 混入、插件、插槽、vuex、本地存储
    【混入】#mixin(混入)功能:可以把多个组件共用的配置提取成一个混入对象,不需要在每个组件中都写了使用步骤   。。。【插件】1#1写plugins/index.js2importVuefrom"vue";3importaxiosfrom"axios";4importhunrufrom"@/mixin";......
  • 06-混入-自定义插件-插槽-本地存储-vuex组件通信-页面跳转
    混入mixin在Vue中,混入(mixin)是一种可以在多个组件中重复使用的对象。它允许您将组件中的一些选项提取出来,然后在多个组件中进行重复使用。混入可以包含组件中的任何选项,例如数据、计算属性、方法等。使用步骤在src文件夹下新建一个文件夹,比如mixin,然后再这个文件夹下面新建一......
  • Nuxt2项目Js文件使用Vuex
    背景当前项目是Nuxt2框架,建立了Vuex仓库。通过返回一个函数的形式,建立Vuex代码如下importVuefrom'vue'importVuexfrom'vuex'Vue.use(Vuex)conststore=()=> newVuex.Store({ state:{ name:'abc' }, mutations:{ setName(state,data){ ......
  • 新品NAS主板,支持vPro,类似ipmi可以小试牛刀
    畅网推出全新的Q670-NAS8盘位主板企业级规格,请看下图。这款主板支持vPro,可以远程管理bios安装系统,家用机器服务器级别的待遇享受。vPro平台最为“离谱”的功能:远程管理,别误会,这里的远程管理并非远程管理软件那样的功能,通过英特尔的AMT主动管理技术和英特尔端点管理助手,即可远程......
  • vuex结合websocket使用
    1、创建一个store文件夹,并在其中创建store.js文件,结合vuex:importVuefrom'vue'importVuexfrom'vuex'importcommonfrom"../common/common.js";Vue.use(Vuex)conststore=newVuex.Store({state:{/***是否需要强制登录*/......