前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue状态管理vuex

Vue状态管理vuex

作者头像
羊羽shine
发布2019-07-16 15:42:27
7810
发布2019-07-16 15:42:27
举报
文章被收录于专栏:Golang开发Golang开发
概述

官方网站 https://vuex.vuejs.org/zh/

项目中安装vuex
代码语言:javascript
复制
npm install vuex -S
Helloworld

在项目的src目录下新建一个目录store,在该目录下新建一个index.js文件,我们用来创建vuex实例,然后在该文件中引入vue和vuex,创建Vuex.Store实例保存到变量store中,最后使用export default导出store:

代码语言:javascript
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})

在main.js文件中引入该文件,在文件里面添加 import store from ‘./store’;,再在vue实例全局引入store对象;

代码语言:javascript
复制
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
State

vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据;

创建store目录 在新创建的store目录下创建index.js

代码语言:javascript
复制
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    num: 1
  },
  mutations: {
    increment(state, num) {
      state.count++
      state.num = num
    }
  },
  actions: {
    inc({commit}, obj) {
      commit('increment', obj)
    }
  }
})

在main.js 导入store

代码语言:javascript
复制
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

设置数据和获取数据

代码语言:javascript
复制
<template>
<div>
  {{msg}}
  <button @click="change">change</button>
</div>
</template>

<script>
    export default {
        name: "HelloVuex",
      data(){
          return{
            msg:234
          }
      },
      methods:{
          change(){
            this.$store.dispatch('inc',100)
            this.msg = this.$store.state.num;
          }
      }
    }
</script>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.07.15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 项目中安装vuex
  • Helloworld
  • State
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档