从Vue.js中的localStorage删除值

时间:2019-07-09 15:05:21

标签: javascript vue.js local-storage vuex

朋友

问题

我有一个问题,当我在视频部分观看特定的剧集时,我之前看到的视频的src被存储在本地存储中。

我的目的是在本地存储离开视频部分后消除其价值。

Local Storage

模板视频

<template>
  <!-- Main -->
  <main class="flex-1 bg-grey-lightest z-0 py-5 px-0">
    <div class="flex flex-wrap max-w-5xl mx-auto">
      <!-- main col -->
      <div class="w-full md:flex-1">
        <!-- player -->
        <div class="bg-black relative mb-3">
          <video 
            id="video"
            controls
          ><source :src="videos.video" type="video/mp4"></video>
        </div>
        <!-- video info -->
        <div class="flex flex-wrap items-end">
          <!-- title -->
          <div class="pb-2">
            <h1 class="text-xl my-2">
              <div class="p-2 bg-indigo-800 items-center text-indigo-100 leading-none lg:rounded-full flex lg:inline-flex" role="alert">
                <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">video</span>
                <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">{{content}}</span>
                <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">{{state}}</span>
                <span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">eps - {{eps}}</span>
                <span class="font-semibold mr-2 text-left flex-auto">{{Title}}</span>
                <svg class="fill-current opacity-75 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.95 10.707l.707-.707L8 4.343 6.586 5.757 10.828 10l-4.242 4.243L8 15.657l4.95-4.95z"/></svg>
              </div>
            </h1>
            <span class="text-base text-grey-darken">{{synopsis}}</span>
          </div>
          <!-- buttons actions -->
          <div class="ml-auto">
            <!-- likes -->
            <div class="flex relative pb-2">
              <!-- like -->
              <div class="flex items-center">
                <span class="text-black opacity-50 text-sm"> ライウアニミー</span>
              </div>
              <!-- hate -->
              <div class="flex items-center ml-5">
                <span class="text-xs text-grey-darken ml-1">?</span>
              </div>
              <div class="absolute w-full h-1 bg-grey pin-b t-5 rounded-full overflow-hidden">
                <div class="absolute pin-l pin-t w-3/4 h-full bg-grey-darkest"></div>
              </div>
            </div>
          </div>
          <hr class="w-full border-t m-0 mb-3 "/>
        </div>
      </div>
    </div>
  </main>
</template>

脚本

我在mount属性中实现的是,如果视频存在,它将消除属于关键vuex的obj视频。

但是我所做的一切并没有做任何事情,当我离开视频部分时,视频对象会保持视频的src。

<script>
  import swal from 'sweetalert';
  import {mapState} from 'vuex'
  import store from '../store/store'
  export default{
    name: 'Video',
    props: ['Id' , 'Title' , 'Eps' , 'Synopsis' , 'ContentType' , 'State'],
    data(){
      return{
        id: this.Id,
        eps: this.Eps,
        synopsis: this.Synopsis,
        content: this.ContentType,
        state: this.State,
      }
    },
    computed:{
      ...mapState(['videos' , 'isLoading'])
    },
    watch:{
      "Eps": function(value){
        this.eps = value;
        let eps = this.eps;
        let info = {id: this.id , eps: eps}
        store.dispatch('GET_ANIME_VIDEO' , info)
        swal("Message!", "Wait a few seconds for the video to load\nIt's normal that it takes a bit", "success");
      },
      "videos.video": function(value){
        this.videos.video = value;
        document.getElementById('video').load();
      }
    },
    mounted(){
      if(this.videos.video){
        const vuex = JSON.parse(localStorage.getItem('vuex'));
        delete vuex.videos;
        localStorage.setItem("vuex", JSON.stringify(vuex));
      }
    },
  };
</script>

突变

我认为我要做的是创建一个突变来清理本地存储

export const mutations = {
  initialiseStore(state) {
    // Check if the ID exists
    if(localStorage.getItem('store')) {
      // Replace the state object with the stored item
      this.replaceState(
        Object.assign(state, JSON.parse(localStorage.getItem('store')))
      );
    }
  },
  SET_LATEST_DATA(state , payload){
    state.latest = payload;  
  },
  SET_VIDEO_ANIME(state , payload){
    state.videos = payload;
  },
  SET_ANIME_ALPHA(state , payload){
    state.animesByAlpha = payload;
  },
  SET_ANIME_GENDER(state , payload){
    state.animesByGender = payload;
  },
  SET_ANIME_SEARCH(state , payload){
    state.searchAnimeList = payload;
  },
  SET_GET_SCHEDULE(state , payload){
    state.schedule = payload;
  },
  SET_MOVIES(state , payload){
    state.movies = payload;
  },
  SET_OVAS(state , payload){
    state.ovas = payload;
  },
  IS_LOADING(state , payload){
    state.isLoading = payload;
  }
};

操作

 GET_ANIME_VIDEO({commit} , info){
    console.log("id: " , info.id , "chapter: " , info.eps)
    A.get(`${API_URL_ENDPOINT.video}` + "/" + `${info.id}` + "/" + `${info.eps}`)
      .then((res) =>{
        console.log("video src = " , res.data)
        commit('SET_VIDEO_ANIME' , res.data);
        commit('IS_LOADING' , false);
      }).catch((err) =>{
      console.error(err);
    });
  },

2 个答案:

答案 0 :(得分:1)

解决方案

对于这样的事情,我将使用Vue生命周期挂钩beforeDestroy

  

在销毁Vue实例之前调用。在此阶段,实例仍然可以正常运行。

示例:

export default {
  // ... vue component stuff ...
  beforeDestroy () {
    localStorage.removeItem('vuex');
  }
}

说明

这将确保在从虚拟AND真正DOM中删除实例之前,我们正在从localStorage中删除名为vuex的项目。

请注意,这不会清除Vuex中存储的状态。为此,您需要创建一个变异并以相同的方式从beforeDestroy()调用该变异。

希望这会有所帮助!

答案 1 :(得分:0)

我的解决方案

我找到了解决方案,但是我不知道它是否是最佳的。但是他负责清洁。

beforeDestroy(){
  const vuex = JSON.parse(localStorage.getItem('vuex'));
  if(vuex.videos){
    localStorage.removeItem(vuex.videos);
  }
}

实际问题

当我离开视频会话并想去看另一个视频时,上一个视频的屏幕保持不变

我的目的是使屏幕保持黑屏并将视频的分钟数保持为零

enter image description here