美文网首页
Vuex 的使用方式(初级版)

Vuex 的使用方式(初级版)

作者: 阿畅_ | 来源:发表于2018-12-24 23:53 被阅读23次
  • vuex 的使用场景: 例如:几个不相关的组件想要共享一个数据的状态 -> Vuex 官方文档的说话是当遇到 ·多个组件共享状态时·可以用到Vuex
  • 来自官方文档的图片.png
  • state 可以理解为是所有组建想要共享的数据
  • mutations 是定义改变 state 的数据
  • actions 是什么时候改变 state 的数据 -> 提交 commit
  • 总结就是: 数据放在 state 里,怎么改变通过 mutations 进行改变,什么时候改变的行为都放在 actions
  1. Vue 模板 render 数据 (state)
  2. components 接受用户的交互,触发 actions ,通过 dispatch 触发
  • Vuex 小例子:
    • main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  count: 1
}

const mutations = {
  increment (state) {
    state.count += 1
  },
  decrement (state) {
    state.count -= 1
  }
}

const actions = {
  increment: ({commit}) => {
    commit('increment')
  },
  decrement: ({commit}) => {
    commit('decrement')
  }
}
const store = new Vuex.Store({
  state,
  mutations,
  actions
})
new Vue({
  el: '#app',
  render (h) {
    return h(App)
  },
  store
})

  • app.js
  <template>
  <div id="app">
    <img src="./assets/logo.png">
    <div>{{ $store.state.count }}</div>
    <button @click="increment">增加</button>
    <button @click="decrement">减少</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'App',
  data () {
    return {
      msg: 'hello world'
    }
  },
  methods: mapActions([
    'increment',
    'decrement'
  ])
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

相关文章

  • Vuex 的使用方式(初级版)

    vuex 的使用场景: 例如:几个不相关的组件想要共享一个数据的状态 -> Vuex 官方文档的说话是当遇到 ·多...

  • Vuex 初级使用

    actions 所有异步操作只能放在actions 中 Action 可以包含任意异步操作。(为了告诉自己的,怕忘...

  • vue

    $ cnpm install vue vuex 流程讲解 使用vuex的方式,点击按钮 → dispatch ac...

  • 181219|mpvue如何通过 vuex 实现原生 stora

    mpvue 中使用vuex 的两种方式 麻烦版 在 src目录下创建 store.js文件 页面的 index.v...

  • Vuex二次封装,直接渲染页面,刷新界面不丢失。

    开门见山地说,我们在使用Vuex的时候,经常会遇到使用方式麻烦,刷新之后Vuex丢失等问题。 目录结构以及main...

  • vuex的一些思考

    vuex其实就是一个升级版的eventBus,eventBus的原理很简单,就是个观察者模式,vuex的使用场景无...

  • 英语听力——磨耳朵的打开方式章

    推荐几个磨耳朵的打开方式。 1.初级&进阶版 推荐使用TOEFL听力练习,既有日常对话和交流(conversati...

  • vue组件通信---provide / inject方式

    背景: 在公司开发的组件库中,组件之间的共享值使使用vuex的方式,这种方法严重依赖了vuex,在组件使用的时候...

  • vuex的基本概念

    一、什么时候使用Vuex 如果应用比较简单,就不需要使用Vuex,直接使用父子组件传值及及它传值方式即可,使用Vu...

  • vuex

    一、什么时候使用Vuex 如果应用比较简单,就不需要使用Vuex,直接使用父子组件传值及及它传值方式即可,使用Vu...

网友评论

      本文标题:Vuex 的使用方式(初级版)

      本文链接:https://www.haomeiwen.com/subject/febyhqtx.html