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>
<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')


1万+

被折叠的 条评论
为什么被折叠?



