美文网首页
vue高级进阶

vue高级进阶

作者: 雨未浓 | 来源:发表于2019-10-08 19:55 被阅读0次

    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 () {
      }
      ...     //  省略
    })
    

    相关文章

      网友评论

          本文标题:vue高级进阶

          本文链接:https://www.haomeiwen.com/subject/xmdipctx.html