vue高级进阶

9次阅读

共计 1776 个字符,预计需要花费 5 分钟才能阅读完成。

Vuex

1.state 的使用

首先在 src 文件夹下面建一个 store 文件夹作为仓库
store 里创建一些 js 文件作为相对应的存储空间
例如 store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state: {                   // 状态管理
  count: 1
},
getters: {                // 获取状态值
  getCount: function(state){return state.count * 5}
},
mutations: {         // 操作状态
  add: function(state){state.count += 1}
},
actions: {            // 异步操作状态
  addFun: function(context){context.commit('add')
  }
}
})

在 vue 组件中使用

在插值表达式里  {{$store.state.count}}
computed:{count(){return this.$store.state.count}
}
更新 state 的值
methods: {change(){this.$store.commit('add',args)    // 同步操作,可以有选择性的传参
  },
  asyncChange() {this.$store.dispatch('addFun')   // 异步操作
  }
}

2.mapState 的使用

1. 在.vue 组件中引入, 在 js 块中引入

import {mapState} from 'vuex'

2. 在.vue 组件中使用,一般放在 computed 里可以监听到状态改变

computed:{
  ...mapState([        //mapState 本是一个函数,在里面写一个数组,记得加...‘num’,// 存的数据‘id’])
}
或
computed: {
  ...mapState({num: (state)=>state.num,     // 这种用法可以看作为起别名
    id: (state)=>state.id
  })
}

mapAction 的使用
正常 action 的使用
this.$store.dispatch('function',args)

mapAction
import {mapActions} from 'vuex'
 methods: {...mapActions(['fun1','fun2','fun3'])
或
...mapActions({
  fun1: 'fun1',
  fun2: 'fun2'
  })
}

mapMutations 的使用  // 关于传参问题,直接在调用的地方传参
正常 mutation 的使用
this.$store.commit('function',args)

mapMutations 的使用
import {mapMutations} from 'vuex'
methods:{...mapMutations(['fun1','fun2'])
或
...mapMutations({
  fun1: 'fun1',
  fun2: 'fun2'
})
}

混入 (mixin)

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
** 组件的思想主要是用来解决重复码有相似功能的代码,并使其标准化,统一化,但在前端更多是体现在界面上的视觉效果,如果要实现功能大体相同,界面需要个性化,但又不想传入过多的 props 怎么办呢
这时 mixin 便有了其用武之地,可以使用相同的 js 逻辑,template 和 css 自定义就好了 **

具体使用:
先在 src 下建一个文件夹 mixin
然后在该文件夹下创建你需要按功能取名的 js 文件
例如 common.js

const toggle = {      // 你需要引入哪些就加哪些
data(){return {}
},
created(){},
methods:{} 
...                        // 还可以添加   
}
export toggle

在.vue 文件中使用

import {toggle} from '@/mixin/common.js'
export default {mixins: [toggle]
}

注意:如果混入里的东西和组件内的有冲突,会使用组件内的,欲安内必先攘外

全局混入
在 main.js 中定义

Vue.mixin({created: function () { }
  ...     //  省略
})

正文完
 0