Vuex就是专为 Vue.js 应用程序开发的数据读写工具
参考官方文档
开始 | Vuexvuex.vuejs.org- state就是数据
- mutations就是对数据的改动
- commit就是调用mutations里的操作(以字符串的形式)
与vue不同它需要通过commit来触发事件
Vue.use(Vuex)会在Vue的原型上绑定一个共用属性,把store绑到Vue.prototype上
Vue.prototype.$store = store
从Vue组件里获取Vuex的状态,使用计算属性
Vuex小结
在组件里使用它时,读的时候分为使用对象语法还是类语法,对象语法就使用computed,
this.$store.state.count
使用类语法(JS/TS)
get
如果要写这个API的时候使用$store配合commit
this.$store.commit('xxx',payload)//payload是一个普通值或者对象
此时无法获取commit的返回值,如何去获取?
this.$store.commit('setTag')
然后在
const store = new Vuex.Store({
state:{
count:0;
tag:undefined;
},
mutations:{
addCount(state){state.count+=1}
}
再去读
store.state.tag
注意在安装的时候
1、Vue.use(Vuex)
2、要把store传进去
new Vue({
store,
})
在ts中使用mixins参考vue class component
Extend and Mixins | Vue Class Componentclass-component.vuejs.org// mixins.js
import Vue from 'vue'
import Component from 'vue-class-component'
// You can declare mixins as the same style as components.
@Component
export class Hello extends Vue {
hello = 'Hello'
}
@Component
export class World extends Vue {
world = 'World'
}
使用
import Component, { mixins } from 'vue-class-component'
import { Hello, World } from './mixins'
// Use `mixins` helper function instead of `Vue`.
// `mixins` can receive any number of arguments.
@Component
export class HelloWorld extends mixins(Hello, World) {
created () {
console.log(this.hello + ' ' + this.world + '!') // -> Hello World!
}
}
在Labels.vue和Tags.vue里都使用过了createTag因此可以使用mixins