Vuex学习

第一天开始学习vuex,官网的文档看得有点蒙就百度了一下。

脚手架用的是vue-cli,

然后npm install vuex --save


首先,我在src下创建了一个store.js文件,一个简单的数值加减方法

内容如下:

import Vue from 'vue';  //引用Vue
import Vuex from 'vuex';   //引用vuex

Vue.use(Vuex); //把vuex插件添加进vue里

const state = {
  count: 10    //初始化数值为10
}

const mutations = {
  add(state) {      //加法
    state.count += 1;
  },
  reduce(state) {   //减法
    state.count -=1;
  }
}

export default new Vuex.Store({   //把vuex暴露出去,顺便把上面定义的变量添加进来
  state,
  mutations
})

然后在components下创建一个组件count.vue

内容如下:

<template>
    <div>
      <h1>我是Count</h1>
      <h2>{{msg}}</h2>
      <h3>{{$store.state.count}}</h3>
      <div>
        <hr/>
        <Foo></Foo>
        <hr/>
      </div>
      <div>
        <button @click="$store.commit('add')">+</button>
        <button @click="$store.commit('reduce')">-</button>
      </div>
    </div>
</template>

<script>
  import store from '../store.js'
  import Foo from './Foo.vue'
  console.log(store)
  export default {
    components: {
      Foo
    },
    store,
    data(){
      return {
        msg: `Hello Vuex`
      }
    },
  }

</script>

引用之前创建的store.js文件,然后在模板上直接使用$store.state.count就可以绑定到store.js里的count变量了,

在两个 + - 方法里添加$store.commit('add'),$state.commit('reduce'),相当于on调用store.js里定义的方法吧,刚学还没仔细研究,我就先这样理解了

看到了,我还引用了一个Foo组件是为了看看不同组件是不是会同步变化:

也是在components里创建Foo组件:

<template>
  <div>
    <h1>我是Foo</h1>
    <div>
      <h2>{{$store.state.count}}</h2>
    </div>
  </div>
</template>

<script>
  import store from '../store';
  export default {
    name:'Foo',
    store,
    data() {
      return {

      }
    }
  }
</script>

上面的store.js和count.vue是我在百度的时候看到别人这样写的,为了demo完整就直接搬过来了。暂时先这样。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值