Vuex
Vuex:用于管理数据的工具(对象),读写数据
初始化
//min.ts
new Vue({
store //store:store
})
//index.ts
Vue.use(Vuex); //将store绑到Vue.prototype上
const store = new Vuex.Store({
state: { //相当于data
count: 0
},
mutations: { //相当于methods
increment (state, n: number) {
state.count += n;
}
}
});
export default store;
//使用
console.log(store.state.count); //拿到state数据 //0
store.commit('increment'); //调用increment方法
console.log(store.state.count);//1
在组件中使用Vuex
<div>
<button @click="add"> +1</button>
{{ count }}
</div>
import store from '@/store/index.ts';
@Component({
computed: { //用computed监听count的变化,否则只能初始化监听一次
count () {
return store.state.count; //读
}
}
})
add () {
store.commit('increment',1) //写
//this.$store.commit('increment',1)
}
鉴于以上操作较复杂,vuex提供了一个操作
用this.$store,直接传
<div>
<button @click="add"> +1</button>
{{ count }}
</div>
读(在对象中的写法)
@Component({
computed: { //用computed监听count的变化,否则只能初始化监听一次
count () {
return this.$store.state.count; //读
}
}
})
读(在类中的写法)
get count () {
return this.$store.state.count; //读
}
写
add(){
this.$store.commit('increment', 1); //写
}
注意:commit没有返回值,且只接受两个参数,如果有多个参数可用对象的写法
updateTag (state, payload: { id: string; name: string }) {
const { id, name } = payload //取值 es6析构语法,id和name来自于object
//const id = payload.id
//const name= payload.name
}
既然这些变量在this上面,那就可以直接用
<div>
<button @click="$store.commit('increment',1)"> +1</button>
{{ count }}
</div>
![](https://img.haomeiwen.com/i25004506/a2f9f7ad5ab8df71.png)
Vuex使用mixin
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export class TagHelper extends Vue {
xxx(){} //需要mixin的方法
}
export default TagHelper
使用
import { mixins } from 'vue-class-component'
@Component({
mixins: [tagHelper]
})
export default class Tags extends mixins(tagHelper) {
//会自动读取mixin的方法,就不用再写一遍了
}
网友评论