export default{ name: "app", components: { HellowWorld }, computed: { count(){ return this.$store.state.count; } } };
//count++实战 main.js中 1.state中创建count字段 import Vuex from "vuex" Vue.use(Vuex) const store = new Vuex.Store({ state:{ count:0 } }) new Vue({ store, ... }) 2.mutations中创建一个count++的mutation const store = new Vuex.Store({ state:{ count:0 }, mutations:{ countIncrease(state){ state.count++ } } }) mutations实现了, 然后在页面模板里面拿到这个state的count, 在app.vue这个组件里面 this.$store.state.count ps:如何获取vuex中state的数据? ①直接通过vue store这个实例 this.$store.state.count 4'50 ②通过vuex提供的... 3.button新增click事件触发mutation改变count <button @click="countIncrease">点我自增</button> countIncrease(){ this.$store.commit("countIncrease"); } 扩展:commit的第二个参数使用 在main.js中 mutations:{ countIncrease(state,v){ state.count = v; } } 在app.vue中 countIncrease(){ const v = 100;//自定义的值 this.$store.commit("countIncrease",v); }
Vetur 插件自动补全vue语法
状态管理数据
状态管理动作(通常vuex的对象属性需要传入,然后进行操作例如state)
获取vuex里的state数据
方式1:通过vuex的store实例(通过this.$store指向vuex实例)如图
方式2:通过vuex提供的mapState方法(它是一种function,通过结构的方式获取数据。
外部修改vuex的状态管理数据(通过vuex的commit方法,commit方法的第一个参数,就是mutation状态管理动作的名称,commit方法的第二个参数,可以用来在状态管理动作中获取到,并进行操作)
在main.js中写入
new Vuex.Store({
state:{count:0},
mutations{
conuntIncreaseP(state){
state.count++
}
}
}}
【通过两种方式获取,store实列获取,通过mutation获取】
{{ this.$store.state.count}}
【通过点击事件改变count】
<button> @click="countcrease">点击我</button>
methods{
countcrease(){
this.$store.commit('conuntIncreaseP')
}
}
【mutation 的传值】
new Vuex.Store({
state:{count:0},
mutations{
conuntIncreaseP(state,value){
state.count = value;
}
}
}}
====
methods{
countcrease(){
this.$store.commit('conuntIncreaseP',100)
}
}
vuex中的mutation接收参数
视图中调用mutation的方法传值
视图中去触发mutation中的修改state状态的方法
从state中取值
创建mutations
Store仓库数据源的建立