Vue-Vuex(六)

    科技2024-05-20  80

    Vuex中管理的对象属性都是响应式的

    我们可以在各组件中直接使用this.$router,this.$route,this.$store是因为在Vue.use(插件)的时候会执行插件.install()。他俩的install()会给Vue的prototype加上$router和$route和$store,所以以后在各组件中才能直接获取到。而new Vue时传入的options中的router和store就是给到时候往原型上加属性时准备的值

    const store = new Vuex.store({ state: {//涉及到一个'单一状态树'的概念。大白话就是整个程序最好只有一个store对象,只有一个state对象。都写到一起方便管理 counter: 0, students: [//通过this.$store.state.students调用 {'name':'jilegeji','age':22}, {'name':'codewhy','age':18} ] }, mutations: {//官方推荐使用mutation来修改state。可以不经过actions,直接调用mutations。但是注意不要在这里进行异步操作。 increment(state) {//由事件类型type和回调函数handle组成。handle函数的第一个参数就是state对象,可以直接使用。通过this.$store.commit('increment')调用 state.counter++ }, addStudent(state,stu){//第二个参数被称为是mutation的载荷payload,可以是单个值,也可以是一个对象。 state.students.push(stu) } }, actions: {//最重要的就是第一个参数context。actions中做一些异步处理操作,可以返回Promise对象 }, getters: {//相当于组件中的computed,也相当于是属性的感觉。对state中的属性进行再加工返回。getters默认是不能传递参数的,可以参考下面的moreAgeStu方式实现。 more20stu(state){//通过this.$store.getters.more20stu调用 return state.students.filter(stu => stu.age>20) }, more20stuLength(state,getters){//同样可以直接传入getters对象。 return getters.more20stu.length }, moreAgeStu(state){//这里不能直接将age作为参数传入。//通过this.$store.getters.moreAgeStu(age)调用 return function (age){ return state.students.filter(stu => stu.age>age) } } }, modules: { a: moduleA, b: moduleB } })

    mutation的提交风格

    1.普通提交:this.$store.commit(‘increment’,5)。这种方式mutation中第二个参数就是5 2.特殊提交:this.$store.commit({‘type’:‘increment’,‘count’:5})。这种方式mutation中第二个参数就是传递的对象。

    数据的响应式

    有些操作可能不会触发响应式。各版本之间好像也有区别,遇到问题在具体百度吧。 一般属性都是初始化定义好的才能响应式。直接添加属性和删除属性或者一些特殊情况(比如数组元素替换)可能不会触发响应式 Vue.set()//直接修改值不能触发响应式,可以通过该方法修改 Vue.delete()//直接删除不能触发响应式,可以通过该方法修改 js中删除对象的某属性delete state.info.age

    mutations的类型常量

    随着mutations中的方法越来越多,官方推荐将所有的事件类型type(就是方法名)抽取出来,当作类型常量,具体百度。参考链接

    官方推荐使用mutation修改state的原因是可是使用devtools。但同时也要注意mutation中不能有异步代码,否则devtools也是无法正常记录的。

    modules

    当使用了moduels时要注意用法上的变化 1.state this.$store.state.a.state属性 2.mutation 用法上没有变化,依然是this.$store.commit()。注意各module内名字不要重复。 3.getters 用法上没有变化,依然是this.$store.getters.xxx。注意各module内名字不要重复。此外,在module中的getters还可以有第三个参数,如下: more20stuLength(state,getters,rootState){//rootState就是父state //some code } 4.actions 用法上没有变化,依然是this.$store.dispatch()。注意context的含义。可以打印context看下就明白context里都有什么了。这里还涉及到es6的解构语法。{ commit, state, dispatch }就是contex中的一些属性

    Processed: 0.011, SQL: 8