vue-cli中使用vuex 刷新後數據消失問題
阿新 • • 發佈:2018-08-27
com vue cal 瀏覽器 效果 名稱 rip sea 產品
vue-cli中使用vuex 刷新後數據消失問題
這個時候要用localStorage
參考
//使用情況 其他代碼省略 //Header.vue中 <template> <div id="header"> <div class="s-input"> <input type="text" class="search" placeholder="請輸入您要搜索的產品名次、型號或名稱" v-model="searchVal"/> <input type="submit" class="s-submit" value="搜索" @click="searchIt()"/> </div> </div> </template> <script> import store from ‘../store/index.js‘ export default { data(){ return{ searchVal:‘‘, } }, methods: { searchIt(){ var self = this if(this.searchVal==‘‘){ alert(‘輸入不能為空‘) }else{ $.ajax({ url: ‘https://erienniu.xyz/api/search?page=1&keyword=‘+this.searchVal+‘&select=‘, type: "GET", dataType: "jsonp", //指定服務器返回的數據類型 data: "{}", success: function(data) { //localStorage var storage=window.localStorage; if(!window.localStorage){ alert("瀏覽器不支持localstorage"); return false; }else{ storage.setItem("result",JSON.stringify(data.data.item)); } }, error: function(error) { console.log(error) } }); } this.$router.push({ path:‘/search‘, query: { page: ‘1‘, select: ‘‘, keyword: this.searchVal, }, }) } }, } </script>
router中配置
{
path:‘/search‘,
name: ‘Result‘,
component: Result
},
//Result.vue <template> <div class="itemsBox"> <div class="item" v-for="(item,index) in this.result" :key=‘index‘> <img :src="item.picture"/> </div> </div> </template> <script> import store from ‘../store/index.js‘ export default{ data(){ return{ result: JSON.parse(localStorage.getItem(‘result‘)) } } } </script>
這個時候刷新不會丟失數據,但是再次在header的搜索框中搜索時發現數據不更新,因為result組件沒有重新渲染數據。所以我想在點擊搜索按鈕的時候重新加載result組件
首先是App.vue
<template> <div id="app"> <Header></Header> <router-view v-if="isRouterAlive"></router-view> <Footer></Footer> </div> </template> <script> import Header from ‘./components/Header‘ import Footer from ‘./components/Footer‘ import store from ‘./store/index.js‘ export default { name: ‘app‘, provide (){ return { reload:this.reload } }, data(){ return { isRouterAlive:true } }, methods:{ reload (){ this.isRouterAlive = false this.$nextTick(function(){ this.isRouterAlive = true }) } }, components: { Header, Footer, }, } </script>
Header.vue中增添兩處代碼
export default {
inject:[‘reload‘], //添加這句
data(){
return{
searchVal:‘‘,
}
},
methods: {
searchIt(){
var self = this
if(this.searchVal==‘‘){
alert(‘輸入不能為空‘)
}else{
$.ajax({
url: ‘https://erienniu.xyz/api/search?page=1&keyword=‘+this.searchVal+‘&select=‘,
type: "GET",
dataType: "jsonp", //指定服務器返回的數據類型
data: "{}",
success: function(data) {
var storage=window.localStorage;
console.log(data);
if(!window.localStorage){
alert("瀏覽器支持localstorage");
return false;
}else{
storage.setItem("result",JSON.stringify(data.data.item));
}
self.reload() //添加這句
},
error: function(error) {
console.log(error)
}
});
}
this.$router.push({
path:‘/search‘,
query: {
page: ‘1‘,
select: ‘‘,
keyword: this.searchVal,
},
})
//self.reload() 本來把這句寫在了這裏,是個坑,
//寫在這裏的話會reload運行完了之後才更新數據,就沒有起到更新數據後重新加載組件的效果
}
},
}
</script>
vue-cli中使用vuex 刷新後數據消失問題