Vuex的使用案例(上)

什么是vuex状态管理?

就是我们vue里的核心数据库

  1. 安装
$ npm install vuex --save
  1. 在main.js 主入口js里面引用store.js
import Vue from 'vue'
import App from './App'
import router from './router' 
import store from './vuex/store'   //引用store.js
Vue.config.productionTip = false  //阻止在启动时生成生产提示 

//vue实例
new Vue({
  el: '#app',
  router,
  store,                           //把store挂在到vue的实例下面
  template: '<App/>',
  components: { App }
})
  1. 在store.js里引用Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)  //注册Vuex

// 定义常量    如果访问他的话,就叫访问状态对象
const state = {
    count: 1
}

// mutations用来改变store状态,  如果访问他的话,就叫访问触发状态
const mutations = {
    //这里面的方法是用 this.$store.commit('jia') 来触发
    jia(state){
        state.count ++
    },
    jian(state){
        state.count --
    },
}
//暴露到外面,让其他地方的引用
export default new Vuex.Store({
    state,
    mutations
})
  1. 在vue组件中使用
    使用$store.commit(‘jia’)区触发mutations下面的加减方法
<template>
  <div class="hello">
      <h1>Hello Vuex</h1>
      <h5>{{$store.state.count}}</h5>
      <p>
        <button @click="$store.commit('jia')">+</button>
        <button @click="$store.commit('jian')">-</button>
      </p>
  </div>
</template>

<!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 -->
<style scoped>
    h5{
      font-size: 20px;
      color: red;
    }
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值