taro之--项目进阶与优化

目进阶与优化

状态管理

在我们实现帖子组件(src/components/thread)时,通过 Taro 内置的 eventCenter 发起了一个事件,把当前帖子的数据注入到一个全局的 GlobalState 中,然后在帖子详情页面再从 GlobalState 取出当前帖子的数据——这种简单的发布/订阅模式在处理简单逻辑时非常有效且清晰。

一旦我们的业务逻辑变得复杂,一个简单的发布订阅机制绑定到一个全局的 state 可能就会导致我们的数据流变得难以追踪。好在这个问题不管是在 React 还是 Vue 社区中都有很好的解决方案。我们会使用这两个社区最热门的状态管理工具:Redux 和 Vuex 来解决这个问题。

  • Redux
  • Vuex

首先安装 vuex:

npm i vuex

在入口文件中注入 Vuex 的 store

src/app.js

import Vue from 'vue'
import Vuex from 'vuex'
import './app.css'

const store = new Vuex.Store({
  state: {
    thread: {},
  },
  mutations: {
    setThread: (state, thread) => {
      state.thread = { ...thread }
    },
  },
})

const App = {
  store,
  render(h) {
    // this.$slots.default 是将要会渲染的页面
    return h('block', this.$slots.default)
  },
}

export default App

然后在帖子组件中我们就可以通过 this.$store.setThread() 设置当前的帖子:

src/components/thread.vue

- eventCenter.trigger(Thread_DETAIL_NAVIGATE, this.props)
+ this.$store.setThread(this.$props)

在帖子详情组件中通过 computed 获取当前帖子的数据:

src/components/thread_detail.vue

{
  data () {
    return {
-     topic: GlobalState.thread,
      loading: true,
      replies: [],
      content: ''
    }
  },
+ computed: {
+  topic() {
+    return this.$store.state.thread
+  }
+ }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞬间的醒悟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值