vuex相关知识点

vuex相关知识点

一、安装:

(1)方法一:

安装vue ui项目可视化工具,安装之后在cmd中输入vue ui命令创建项目

(2)方法二:

1.在项目所在目录 npm install vuex --save安装vuex

2.在src文件夹下新建store.js文件,代码如下

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
 
export default new Vuex.Store({
  state:{
    count:0
  },
  mutations:{
    increment:state => state.count ++,
    decrement:state => state.count --,
  }
})

3.在main.js文件中引入store.js

import store from './store.js'
//实例化
new Vue({
  router,
  store,
  axios,
  el: '#app',
  render: h => h(App)
})

4.接下来,就可以在其他文件(组件)中调用

二、使用方法

1.在store.js文件中,添加state数据(共享数据),mutations存储修改state中数据的方法(只能用这一种方法修改共享数据)

2.获取共享数据

方法一:

this.$store.state.数据名 DOM结构中可简写为: $store.state.数据名

例如:<h3>当前最新的count值为:{{$store.state.count}}</h3>

方法二:在组件中

// 第一步导入mapState函数
import {mapState} from 'vuex'
export default{
  data(){
    return {}
  },
  computed:{
    //第二步将全局数据映射为当前组件的计算属性
    ...mapState(['count'])
  }
}

然后就可以在模板中使用了

<h3>当前最新的count值为:{{count}}</h3>

3.在组件中调用方法,修改state中的数据 (只能通过mutations中的方法修改共享数据:)

(1)直接调用commit方法
commit方法里面引用的方法可以修改共享数据,引用的方法在mutations中定义(相当于还是通过mutations修改共享数据)

this.$store.commit('方法名') (commit的作用: 就是调用某个mutation函数)

store.js文件代码

 state: {//state对象
    count:0
  },
  mutations: {
    add(state){//第一个参数永远是上面的state对象
      state.count++;
    }
  },

组件代码:

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button @click="btnHandler1">+1</button>
  </div>
</template>
<script>
export default {
  data () {
    return {}
    },
  methods:{
    btnHandler1(){
      this.$store.commit('add')
    }
  }
}
</script>

==》注意:commit方法传递参数,只能传递一个,若想传多个参数,以对象方法传递,例如:

this.$store.commit('upp',{a:this.selectedId,b:sPerson})

==》使用时:

mutations:{
  upp(state,nums){//方法的第一个形参永远是state(也就是Vuex中的state)
      // console.log('num1:' + num1)
      // console.log('num2:' + num2)
      state.persons.splice(nums.a,1,nums.b)
    }
}

(2)通过调用mutations中的方法

第一步:在组件中导入mapMutations

import {mapState,mapMutations} from 'vuex'

第二步:将mutations中的方法映射为当前组件的methods方法

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button @click="btnHandler1">-1</button>
     <button @click="btnHandler2">-N</button>
  </div>
</template>
<script>
import {mapState,mapMutations} from 'vuex'//导入
export default {
  data() {
    return {}
  },
  computed:{
    ...mapState(['count'])//映射
  },
  methods:{
    ...mapMutations(['sub','subN']),
   btnHandler1(){
     this.sub()//使用
   },
    btnHandler2(){
     this.subN(3)//带参数的
   }
  }
}
</script>

4.Action的使用(用于处理异步任务)

mutations函数中不能写异步的代码,需要在action里面写异步的方法(但在action里面还是要通过触发mutations 的方式间接变更数据)

5.触发actions的方法

(1)方法一

this.$store.dispatch()

store.js文件

mutations: {
   addN(state,step){
      state.count+=step;
    },
  },
  actions: {
  //第一个参数永远是context
    addAsync(context,step){
      setTimeout(()=>{
        //在actions中不能直接修改state中的数据
        //必须通过context.commit()触发某个mutations才行
        context.commit('addN',step)
      },1000)
    }
  },

组件内代码

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button @click="btnHandler3">+N Async</button>
  </div>
</template>
<script>
export default {
  data () {
    return {}
  },
  methods:{
   //异步地让count自增N
     btnHandler3(){
       //专门使用dispatch触发某个action
      this.$store.dispatch('addAsync',3)
    },
  }
}
</script>

(2)方法二

第一步:在组件中导入mapActions

import {mapState,mapMutations,mapActions} from 'vuex'

第二步:将actions中的方法映射为当前组件的methods方法) (actions中的方法都是异步方法)

methods:{
...mapActions(['subAsync','subNAsync'])
}

第三步:使用

可直接调用映射过来的异步方法,也可传递参数

   //直接使用
    <button @click="subAsync(10)">-N</button>
    //或者
    btnHandler2(){
     this.subAsync(5)
   }

总结:

commit调用mutations里面的方法

dispatch调用actions里面的方法

以上映射的mutations或者actions中的方法,在组件内都可以直接使用,相当于自己内部函数
6.Getter

getter用于对Store中的数据进行加工处理形成新的数据。

不会修改store中的数据,只是起到包装作用,类似Vue的计算属性

store中的数据发生变化,getter中的数据也会跟着变化

使用方法一:

this.$store.getters.名称

store.js文件中

 getters:{
      showNum(state){
        return '当前最新数量是【'+state.count+'】'
      }
    },

组件中:

 <h3>{{$store.getters.showNum}}</h3>

使用方法二:

第一步:在组件中导入mapGetters

import {mapState,mapMutations,mapActions,mapGetters} from 'vuex'

第二步:将getters中的方法映射为当前组件的computed方法)

import {mapGetters} from 'vuex'
computed:{
...mapGetters(['showNum'])
}

第三步:使用

可直接调用映射过来的getter方法

 <h3>{{showNum}}</h3>
7.vuex-persistedstate持久化组件的使用方法

第一步:在项目目录安装组件

npm i -S vuex-persistedstate

第二步:在vuex初始化时(即在store.js文件里)引入

import persistedState from 'vuex-persistedstate'
export default new Vuex.Store({
    // ...
    plugins: [persistedState()]
})
8.vuex-persistedstate多个模块的使用方法

(1)使用vuex-persistedstate插件,可以让vuex自动存储在localstorage中.当我们使用模块的方式划分vuex的时候,vuex-persistedstate会默认将所有的模块都存储在本地。

/**
 * vuex的入口文件
 */
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate/index"

Vue.use(Vuex);

import {article} from "@/store/article";
import {user} from "@/store/user";
import {category} from "@/store/category";
import {editor} from "@/store/editor";

export default new Vuex.Store({
  modules: {
    article,
    user,
    editor,
    category
  },
  plugins: [createPersistedState()]
})

(2)如果只需要持久化存储部分模块

store.js文件

import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
import isopreservation from './modules/isopreservation'
import alarm from "./modules/alarm";
import safe from "@/store/modules/safeWeb";
import persistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    app,
    user,
    isopreservation,
    alarm,
    safe
  },
   plugins: [
    // 需要localStorage存储起来的模块
    createPersistedState({
      storage: window.localStorage,
      paths: ['app', 'user','isopreservation']
    }),
    // 需要sessionStorage存储起来的模块
    createPersistedState({
      storage: window.sessionStorage,
      paths: ['alarm', 'safe']
    })
  ]
  //或者直接这样
  plugins:[persistedState({
    paths: ['safe']
  })]

})

注意:如果不确定其他模块是否使用持久化存储,那么直接按上面第二种方法写

第三步:直接编写项目代码即可

==》注意:vuex-persistedstate默认使用localStorage来固化数据,若想使用sessionStorage,则

plugins: [
    persistedState({ storage: window.sessionStorage })
]
总结:

在初始化时(渲染页面时)添加功能:

created(){
//此处为功能代码
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值