首页 > 其他 > 详细

vue mixins的使用

时间:2018-10-18 21:39:38      阅读:172      评论:0      收藏:0      [点我收藏+]

官网传送

刚开始接触vue的时候,官网关于mixins的例子看了好几遍,发现还是不会用,包括vuex也是后来慢慢理解一点的,不过和vuex比起来。mixns还是很好理解,简单很多了

就我目前理解mixns,它就相当于一个中间件,可以把一些公用的函数,方法放到这个中间件,页面调用的时候只需要引入mixns就行,提高重复利用率

以存储城市历史记录为例:

1. 在src目录下新建mixns目录,下面新建文件getHistoryCity.js

export default{
    methods:{
        setCitys(data){
           let searchCity = sessionStorage.getItem(‘CITY_INFO‘);
                if(!searchCity){//如果没有历史记录
                     let option=[];
                     option.push(data);
                     sessionStorage.setItem(storename,JSON.stringify(option));
                }else{
                    let newSearchCity=JSON.parse(searchCity);
                    if(newSearchCity.indexOf(data)==-1){ // 如果数组中没有,就加进去,最多存9条
                        newSearchCity.push(data)
                        if(newSearchCity.length>9){
                            newSearchCity.splice(1,newSearchCity.length)
                        }
                    }
                    sessionStorage.setItem(storename,JSON.stringify(newSearchCity));
                }
       }, 
getCitys(){
      return JSON.parse(sessionStorage.getItem(‘CITY_INFO‘));
    }

  }
} 

组件或页面里调用 index.vue

<template>
<div class="his_wrap" v-if="historycitys">
          <div class="tit">历史选择城市</div>
          <div class="flex-wrap">
            <div class="his_city" v-for="item in historycitys">{{item}}    
          </div>
          </div>
</div>
</template>

<script>
import historyCityMixin from ‘@/mixins/getHistoryCity‘
export default {
  name:‘index‘,
  mixins:[historyCityMixin],
  data(){
    return{
       historycitys:null
    }
  },
  created(){
    this.historycitys = this.getgetCitys();
  },
  methods:{
    selectCity(item){
       this.setCitys(item)
    }
  }
}
</script>        

 

vue mixins的使用

原文:https://www.cnblogs.com/leiting/p/9813128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!