1、mutations的提交风格
// @/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter: 10
},
getters: {
},
mutations: {
addCounter(state,counter) {
console.log(counter,'哈哈哈哈');
}
},
actions: {
},
modules: {
}
})
mutations普通提交风格
this.$store.commit('addCounter',counter)
结果:
mutations特殊提交风格
handleClick(counter) {
this.$store.commit({
type: 'addCounter',
counter
})
}
结果:
结论:第二种提交方式(mutations特殊提交风格),可以传多个参数
2、store中的state是响应式的条件(什么是响应式?数据一发生变化,页面立即更新)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
info: {
name: 'why',
age: 18,
sex: '男'
}
},
getters: {
},
mutations: {
changeInfoName(state) {
state.info.name = 'tm'
}
},
actions: {
},
modules: {
}
})
this.$store.commit('changeInfoName'
结果:
可证:提前 在state中初始化好的 属性 是响应式的;
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
info: {
name: 'why',
age: 18,
sex: '男'
}
},
getters: {
},
mutations: {
addAttribute(state) {
state.info['location'] = '北京'
}
},
actions: {
},
modules: {
}
})
this.$store.commit('addAttribute')
结果:
可证:未提前 在state中初始化好的 属性 不是响应式的;info对象中已经添加了新的location属性,但是新增的属性没有被vuex监测,它不是响应式的
若想要新增的location属性也是响应式的,可采取下面的方法:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
info: {
name: 'why',
age: 18,
sex: '男'
}
},
getters: {
},
mutations: {
addAttribute(state) {
// state.info['location'] = '北京'
Vue.set(state.info, 'location', '北京')
}
},
actions: {
},
modules: {
}
})
结果:
若想要在info中删除一个属性呢?
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
info: {
name: 'why',
age: 18,
sex: '男'
}
},
getters: {
},
mutations: {
removeAttribute(state) {
delete state.info.age
}
},
actions: {
},
modules: {
}
})
this.$store.commit('removeAttribute')
结果:
发现info对象中的age已经被删除了,但是页面还是存在age,说明js的 delete 也不是响应式的(慎用)
如果想要删除属性也是响应式的呢?
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
info: {
name: 'why',
age: 18,
sex: '男'
}
},
getters: {
},
mutations: {
removeAttribute(state) {
// delete state.info.age
Vue.delete(state.info, 'age')
}
},
actions: {
},
modules: {
}
})
结果: