Vuex之集成

安装 vuex

npm i vuex -S

创建文件夹

创建 client/ store/

创建 client/store/store.js 应用入口

声明 store

// store.js
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    updateCount (state, num) {
      state.count = num
    }
  }
})

export default store
复制代码

store 的引入

// index.js 应用入口(最外层)
import Vuex from 'vuex'
import store from './store/store'  // 引入

Vue.use(Vuex)

const root = document.createElement('div')
document.body.appendChild(root)

new Vue({
  router, 
  store, // 注册
  render: (h) => h(App)
}).$mount(root)
复制代码

store 的使用

显示 store 数据

// app.vue 根组件
<template>
  <div id="app">
    <p>{{count}}</p> // 显示 0
</template>

<script>
export default {
  mounted () {
    console.log(this.$store)
  },
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
</script>
复制代码

组件内部,调用 $store 的 commit 方法,修改 mutation

// app.vue 根组件
<template>
  <div id="app">
    <p>{{count}}</p> // 每秒加 1
</template>
<script>
    mounted () {
        console.log(this.$store)
        let i = 1
        setInterval(() => {
          this.$store.commit('updateCount', i++)
        }, 1000)
      },
      computed: {
        count () {
          return this.$store.state.count
        }
      }
</script>
复制代码

修改声明的 store

和 vue-router 类似,export 时,需要是一个 function,因为服务端渲染,每次渲染都会新生成一个 store,不能使用同一个 store,使用同一个 store 会有内存溢出的问题。

import Vuex from 'vuex'

export default () => {
  return new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      updateCount (state, num) {
        state.count = num
      }
    }
  })
}

复制代码

对应修改入口文件 store 的引入

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

import createStore from './store/store'

Vue.use(Vuex)

const store = createStore()

const root = document.createElement('div')
document.body.appendChild(root)

new Vue({
  store,
  render: (h) => h(App)
}).$mount(root)
复制代码

转载于:https://juejin.im/post/5b971bc86fb9a05d2a1d4fed

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值