在Vue项目中使用Vuex

一、安装vuex

npm install vuex --save

二、创建store

在项目src目录下创建store目录,在store目录中创建index.js文件。写入一下内容:

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

// 挂在Vuex
Vue.use(Vuex)

// 创建Vuex对象
const store = new Vuex.Store({
    state:{
        // 存放的键值对就是所要管理的状态
        // 以key:value为例
        key : value,
    },
    mutations:{
        setKey(state, payload) {
            state.key = payload;
        }
    }
})

export default store

三、挂载store

在main.js中,添加代码:

···
import store from './store'
···

new Vue({
  el: '#app',
  router,
  store: store, //store:store 和 router一样,将我们创建的Vuex实例挂载到这个vue实例中
  components: { App },
  template: '<App/>'
})

四、在组件中使用

将需要使用的值写在computed中:

computed:{
    key() {
        return this.$store.state.key;
    }
}

如果在组件中使用v-model绑定computed中的值,需要在computed中定义set方法,如下:

computed:{
    key:{
        get(){
            return this.$store.state.key;
        },
        set(val){
            this.$store.commit('setKey', val);
        }
    }
}

五、在Vue组件中监听Vuex

Vue在组件中监听Vuex

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值