Vuex的基本用法

博客介绍了Vuex适用于大型单页应用及多人协同开发。讲述了通过NPM安装Vuex,在main.js里使用Vue.use()启用。还说明了仓库store包含应用数据和操作,数据响应式,组件会随store数据变化更新,以及改变store数据需提交mutations等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vuex主要适用于大型单页应用,适合多人协同开发。(emmm....这是我看书上知道的,先记下来再看是不是。。)

1。通过NPM安装Vuex:

npm install --save vuex

2.与vue-router用法相似,在main.js里通过Vue.use()使用vuex:

import Vuex from 'vuex';

Vue.use(Vuex);

//配置路由省略

const store=new Vuex.Store({

//vuex的配置

});

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

 

仓库store包含了应用的数据(状态)和操作过程。Vuex里的数据都是响应式的,任何组件使用同一store的数据时,只要store的数据变化,对应的组件也会立即更新。

数据保存在Vuex选项的state字段内,比如要实现一个计数器,定义一个数据count,初始值为0:

在main.js中写:

const store=new Vuex.Store({
   state:{
       count:0
   }
});

在index.vue中通过$store.sate.count读取:

<template>
    <div>
        <h1>首页</h1>
        {{count}}
    </div>
</template>
<script>
    export default {
      computed:{
        count(){
          return this.$store.state.count;
        }
      }
    }
</script>

现在访问首页可以显示出来count:0

现在说vuex里面的一些方法:
在组件内,来自store的数据,不能手动改变,改变store中数据的唯一途径就是显式地提交mutations。

mutains是Vuex的第二个选项,用来直接修改state里的数据。我们给计数器增加2个mutations,用来加1和减1:

//main.js

const store=new Vuex.Store({
   state:{
       count:0
   },
    mutations:{
        increment (state,params){
          state.count+=params.count;
        },
        decrease(state){
           state.count--;
        },
    }
})

在组件内通过this.$store.commit方法来执行mutations。在index.vue中添加两个按钮:

<template>
    <div>
        <h1>首页</h1>
        {{count}}
        <button @click="handleIncrement">+1</button>
        <button @click="handleDecrease">-1</button>
         <button @click="handleIncrementMore">+5</button>
    </div>
</template>
<script>
    export default {
      computed:{
        count(){
          return this.$store.state.count;
        }
      },
      methods:{
        handleIncrement(){
          this.$store.commit('increment');
        },
        handleDecrease(){
          this.$store.commit('decrease')
        },
        handleIncrementMore(){
          this.$store.commit({
             type:'increment',
             count:5
          })

        }
      }
    }
</script>

这里的mutations还可以接受第二个参数,可以是数字,字符串或者对象等类型。比如每次不是增加1而是5

修改index.js中的increment代码

increment (state,params){
  state.count+=params.count;
},

在index.vue写:

 handleIncrementMore(){
          this.$store.commit({
             type:'increment',
             count:5
          })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值