vuex的简单使用

要在main.js里引入store文件夹里的index.js

home.vue

<template>
  <div class="home">
    <button @click="clickHandle()">加购物车</button>
    <foot></foot>
  </div>
</template>

<script>

import foot from '../components/footer'
import store from '../store/index.js'
export default {
  name: 'home',
  components: {
    foot
  },
  methods: {
    clickHandle () {
      this.$store.dispatch('addCount')
    }
  },
};
</script>
<style scoped>
button {
  background: deeppink;
  color: #fff;
  border: 0;
  width: 80px;
  height: 50px;
  margin: 100px auto;
}
</style>

footer.js

<template>
  <div class="foot">
    <ul>
      <li>首页</li>
      <li>列表</li>
      <li>购物车({{this.$store.state.count}})</li>
      <li>我的</li>
    </ul>
  </div>
</template>
<script>
import store from '../store/index.js'
export default {
  data () {
    return {

    }
  }
}
</script>
<style scoped>
ul {
  position: fixed;
  bottom: 0;
  background: #efefef;
  display: flex;
  height: 50px;
  width: 100%;
  line-height: 50px;
}
li {
  list-style: none;
  width: 25%;
}
</style>

store文件夹里的index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
  },
  mutations: {
    INFOR(state) {
      state.count += 1;
    },
  },
  actions: {
    addCount({ commit }) {
      commit('INFOR');
    },
  },
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在手机端,使用Vuex可以方便地管理应用程序的状态。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态的一致性。 在手机端使用Vuex,首先需要安装Vuex库。可以通过npm或者yarn进行安装。安装完成后,在Vue项目中创建一个store文件夹,并在该文件夹下创建一个index.js文件。 在index.js文件中,需要引入Vue和Vuex,并创建一个新的Vuex.Store实例。在该实例中,可以定义state、mutations、actions和getters等属性和方法。 state:用于存储应用程序的状态数据。 mutations:用于修改state中的数据。只能进行同步操作。 actions:用于处理异步操作,可以包含多个mutations的调用。 getters:用于获取state中的数据,类似于计算属性。 下面是一个简单的示例: ```javascript // index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; }, decrement(state) { state.count--; } }, actions: { incrementAsync(context) { setTimeout(() => { context.commit('increment'); }, 1000); } }, getters: { doubleCount(state) { return state.count * 2; } } }); export default store; ``` 在Vue组件中,可以通过this.$store来访问Vuex的状态和方法。例如: ```javascript // App.vue <template> <div> <p>Count: {{ $store.state.count }}</p> <p>Double Count: {{ $store.getters.doubleCount }}</p> <button @click="$store.commit('increment')">Increment</button> <button @click="$store.dispatch('incrementAsync')">Increment Async</button> </div> </template> <script> export default { name: 'App', mounted() { console.log(this.$store.state.count); } } </script> ``` 以上是手机端使用Vuex简单介绍,希望对你有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值