Vuex入门,复制即用

8 篇文章 0 订阅

首先在 src 下创建 store/index.js

// 导入 vuex
import Vuex from 'vuex'
// 创建仓库 store
const store = new Vuex.Store({
// 相当于vue 里 data return,需要提前声明需要的变量
    state () {
        return {
            count: 2
        }
    },
    mutations: {
     //第一个参数state 相当于vue里的 this,data是调用方法时传的值
        increment (state,data) {
            state.count = data;
        }
    }
});
// 导出仓库
export default store

在main.js里调用

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'.
// 引入创建的storejs
import store from './store'

createApp(App).use(store).mount('#app');

其他组件使用

//直接在标签中使用
<p>数字 {{ $store.state.count }}<p>
// 也可以在js里使用
export default {
  data() {
    return {
    nowCount:''
}
  },
  methods: {
    increaseCount(){
      this.nowCount = $store.state.count;
    }
  },
}

更改数据

clickMsg(){//第一个参数是 store/index.js 定义的方法名,第二个参数是接受的参数
      this.$store.commit('increment',5)
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值