vuex入门的详细使用步骤

一、新建项目

 在webstorm中输入指令:npm create 项目名称  

二、安装Vuex

进入新建好的项目中,输入指令:npm install vuex --save

三、简单使用

在这里插入图片描述
在项目的src目录下新建一个store文件夹,在store目录下新疆一个index.js文件:
在这里插入图片描述 在index.js文件中导入Vue和Vuex

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

通过Vue的use(插件)使用Vuex插件

Vue.use(Vuex)

创建Vuex对象,在state状态中定义一个count变量和两个方法(一个加,一个减)

const store =new Vuex.Store({
   state:{
     count:0
   },
  mutations:{
     add(state){
        state.count++;
     },
     sub(state){
       state.count--;
    }
  }
})

导出Vuex对象至main.js

export default store

进入main.js,导入store(Vuex对象)

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

// 导入Vuex对象
import store from './store/index'

new Vue({
  store,
  render: h => h(App),

}).$mount('#app')

下一步就是到App.vue中把store中的count显示出来,并可以进行加减操作

<template>
  <div id="app">
    <h1>展示vuex中管理的状态</h1>
    <h1>{{$store.state.count}}</h1>
    <button @click="add()">+</button>
    <button @click="sub()">-</button>
    <HelloWorld></HelloWorld>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods:{
    add(){
      this.$store.commit('add')
    },
    sub(){
      this.$store.commit('sub')
    }
  }
}
</script>

<style>

</style>

接下来到Helloworld.vue中进行一样的操作

<template>
  <div class="hello">
   <hr/>
   <h1>{{$store.state.count}}</h1>
    <button @click="add()">+</button>
    <button @click="sub()">-</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  methods:{
    add(){
      this.$store.commit('add')
    },
    sub(){
      this.$store.commit('sub')
    }
  }
}
</script>

<style scoped>

</style>

总结

通过State状态管理数据,其他组件可以将数据并显示出来(View),如果要对数据进行更改,则要通过Actions也就是事件来对state中的数据进行操作。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值