Vuex到底是什么

Vuex到底是什么

现在在学习写一个工程的时候看到很多样例都用到了vuex,那么vuex究竟是什么?

从官网上说, Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态.

这个其实蛮难看懂。于是作者做了如下例子来说明,分别用纯vue和vue+vuex进行说明。

需求是,一个数字,然后两个按钮+/-

纯vue的实现是:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <p>{{count}}
    <button @click="inc">+</button>
    <button @click="dec">-</button>
  </p>
</div>
<script>
new Vue({
  el:'#app',
  data () {
    return {
      count: 0
    }
  },
  methods: {
    inc () {
      this.count++
    },
    dec () {
      this.count--
    }
  }
})
</script>

vue+vuex的实现是:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@next"></script>
<div id="app">
  <p>{{count}}
    <button @click="inc">+</button>
    <button @click="dec">-</button>
  </p>
</div>
<script>

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
      inc: state => state.count++,
    dec: state => state.count--
  }
})

const app = new Vue({
  el: '#app',
  computed: {
    count () {
        return store.state.count
    }
  },
  methods: {
    inc () {
      store.commit('inc')
    },
    dec () {
        store.commit('dec')
    }
  }
})
</script>

这里看到所有涉及到状态和计算都放到了store中,这样就可以在各个组件之间互相传递和共享了,解决了互相通讯的问题。

作者原文链接: 到底vuex是什么?

### 封装 Vuex 中的滚动到底部功能 为了在 Vuex 中实现一个用于检测并处理滚动到底部的功能,可以按照以下方式设计模块化结构。通过监听 `scroll` 事件以及计算当前滚动位置与容器总高度的关系,判断是否已经到达底部。 以下是具体的实现方法: #### 创建 Vuex 模块 创建一个新的 Vuex 模块(例如命名为 `scrollBottomModule`),该模块负责管理滚动状态和触发加载更多数据的操作。 ```javascript // store/scrollBottomModule.js const state = { isScrollingToBottom: false, }; const mutations = { SET_SCROLLING_TO_BOTTOM(state, value) { state.isScrollingToBottom = value; }, }; const actions = { handleScroll({ commit }, { containerSelector }) { const container = document.querySelector(containerSelector); if (!container) return; container.addEventListener('scroll', () => { const scrollTop = container.scrollTop; const scrollHeight = container.scrollHeight; const clientHeight = container.clientHeight; // 判断是否接近底部 (留有一定缓冲距离) if (scrollTop + clientHeight >= scrollHeight - 10) { commit('SET_SCROLLING_TO_BOTTOM', true); // 设置为已到最底 } else { commit('SET_SCROLLING_TO Bottom', false); // 还未达到最底 } }); }, loadMoreDataIfAtBottom({ state, dispatch }, payload) { if (state.isScrollingToBottom) { dispatch('loadMoreData', payload).then(() => { commit('SET_SCROLLING_TO_BOTTOM', false); // 加载完成后重置标志位 }); } }, async loadMoreData(_, params) { try { // 调用 API 或其他逻辑获取新数据 console.log(`Loading more data with parameters: ${JSON.stringify(params)}`); // 假设返回新的数据列表 return await new Promise((resolve) => setTimeout(resolve(['newItem1', 'newItem2']), 1000)); } catch (error) { console.error('Failed to load more data:', error); } }, }; ``` 上述代码实现了以下几个核心部分: - **State**: 存储是否正在滚动至底部的状态。 - **Mutations**: 提供修改 State 的能力。 - **Actions**: 处理异步操作,包括绑定滚动事件、检测是否滚到底部以及调用接口加载更多数据[^3]。 #### 组件中的集成 接下来是在 Vue 组件中使用这个 Vuex 功能的例子。 ```html <template> <div class="scroll-container"> <div v-for="(item, index) in items" :key="index">{{ item }}</div> </div> </template> <script> import { mapActions } from 'vuex'; export default { data() { return { items: ['initialItem1', 'initialItem2'], }; }, mounted() { this.handleScroll({ containerSelector: '.scroll-container', }); }, methods: { ...mapActions([ 'handleScroll', 'loadMoreDataIfAtBottom' ]), onScroll() { this.loadMoreDataIfAtBottom(); }, }, }; </script> <style scoped> .scroll-container { height: 400px; /* 可调整 */ overflow-y: auto; } </style> ``` 此模板展示了如何将 Vuex 的滚动控制逻辑嵌入到实际应用中,并动态更新显示的数据项[^4]。 #### 注意事项 当尝试结合 better-scroll 实现更复杂的交互体验时,需注意其内部机制可能会影响原生 DOM 的行为模式。因此建议参考相关文档配置合适的参数以兼容自定义需求[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值