2021-01-07

1、state

在组件中使用Vuex

<div class="HelloWorld">
  <h1>{{ $store.state.name }}</h1>
</div>

或在组件方法中使用

methods:{
   print(){
      console.log(this.$store.state.name)
    }
}

在Vue项目开发中,需要监控项目中得各种值,为了提高效率,Vue提供了一款浏览器扩展——VueDevtools。

如何安装?(谷歌浏览器)
在这里插入图片描述
在这里插入图片描述
这里还有更多方法:https://www.cnblogs.com/alice-fee/p/8038367.html(转载)

在vueDevtools中监控项目中的各种值
在这里插入图片描述
2、Mutations

mutations是操作state数据的方法的集合,比如对该数据的修改、增加、删除等等。

2.1 Mutations使用方法

mutations方法都有默认的形参:

([state] [,payload])

·state是当前VueX对象中的state
·payload是该方法在被调用时传递参数使用的

我们编写一个方法,当被执行时,能把下例中的name值修改为"jack",我们只需要这样做

index.js

//挂载Vuex
Vue.use(Vuex)

//创建VueX对象
const store = new Vuex.Store({
    state:{
        //存放的键值对就是所要管理的状态
        name:'helloVueX'
    },
    mutations:{
        //es6语法,等同edit:funcion(){...}
        edit(state){
            state.name = 'jack'
        }
    }
})
export default store

HelloWorld.vue

<template>
  <div class="HelloWorld">
    <h1>{{ $store.state.name }}</h1>
    <button @click="print">点击按钮在控制台输出内容</button> &nbsp;
    <button @click="edit">点击按钮改变输出内容</button>
  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    },
    methods:{
        print(){
          console.log(this.$store.state.name)

        },
        edit(){
          this.$store.commit('edit')
        }
    }
  }
</script>

效果:
在这里插入图片描述
2.2 Mutation传值:

在实际生产过程中,会遇到需要在提交某个mutation时需要携带一些参数给方法使用。

提交单个值时:

this.$store.commit('edit',15)

收到挂载的参数:
在这里插入图片描述
当需要多参提交时,推荐把他们放在一个对象中来提交:

this.$store.commit('edit',{age:15,sex:'男'})

收到挂载的参数:
在这里插入图片描述
我们也可以这样写:

this.$store.commit({
    type:'edit',
    payload:{
        age:15,
        sex:'男'
    }
})

2.3 增删state中的成员

为了配合Vue的响应式数据,我们在Mutations的方法中,应当使用Vue提供的方法来进行操作。

2.3.1 Vue.set 为某个对象设置成员的值,若不存在则新增

例如:对state对象中添加一个school成员

Vue.set(state,"school",'xxxx')

2.3.2 Vue.delete 删除成员

将刚刚添加的school成员删除

Vue.delete(state,'school')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值