vuex study第一节

引入vuex

1.利用npm包管理工具,进行安装 vuex。在控制命令行中输入下边的命令就可以了。

npm install vuex --save

2.新建一个vuex文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。
这里写图片描述
然后写store.js

import Vue from 'vue'
import Vuex from 'vuex'
//安装vuex
Vue.use(Vuex)
//声明状态常量对象
const state = {
    count: 1
}
//需要改变state的值,必须通过mutations,意思为改变
//在mutations里声明方法
const mutations = {
    add(state){
        state.count++;
    },
    reduce(state){
        state.count--;
    }
}
//导出
export default new Vuex.Store({
    //导出状态常量
    state,
    //导出mutations
    mutations
})

创建新组件Count.vue

<template>
    <div>
        <h1>{{ msg }}</h1>
        <!--直接引用store里的数据-->
        <h2>{{ $store.state.count }}</h2>
        <!--提交store里mutations内的方法-->
        <button @click="$store.commit('add')">+</button>
        <button @click="$store.commit('reduce')">-</button>
    </div>
</template>

<script>
    import store from '../vuex/store'
    export default {
        data(){
            return {
                msg: 'Hello Vuex!'
            }
        },
        //将store添加到实例
        store
    }
</script>

<style>
</style>

配置路由

import Count from '@/components/count'

export default new Router({
//  mode:'history',//是否现显示地址栏hash那个#号
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/count',
      name: 'count',
      component: Count
    }
  ]
})

另外也可以在main.js中引入store成为全局的

import store from '@/vuex/store'
Vue.use(store)

new Vue({
  el: '#app',
  store,//将store添加到vue实例
  router,
  template: '<App/>',
  components: { App }
})

这里写图片描述

提示:引入文件路径中的@表示src路径,是自动在webpack.base.conf.js里面配置的
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值