vue sessionstorage存取数组
时间: 2023-08-15 20:06:45 浏览: 66
要存储一个数组到SessionStorage中,可以使用JSON.stringify()方法将其转换成字符串,然后使用SessionStorage.setItem()方法将其存储到SessionStorage中。例如:
```
// 假设要存储的数组为arr
sessionStorage.setItem('myArray', JSON.stringify(arr));
```
要从SessionStorage中获取存储的数组,可以使用JSON.parse()方法将其转换回数组,然后再进行操作。例如:
```
// 获取存储的数组
var arr = JSON.parse(sessionStorage.getItem('myArray'));
// 对数组进行操作
arr.push('new item');
// 重新存储数组
sessionStorage.setItem('myArray', JSON.stringify(arr));
```
注意:存储到SessionStorage中的数据类型只能为字符串,因此需要进行转换。同时,SessionStorage的大小限制为5-10MB,因此需要注意存储的数据大小。
相关问题
vue vuex存取数组
在Vue中,可以使用Vuex来管理全局的状态。要在Vuex中存储一个数组,可以通过定义一个数组类型的state来实现。例如:
```
const store = new Vuex.Store({
state: {
myArray: []
},
mutations: {
setMyArray(state, newArray) {
state.myArray = newArray;
}
}
});
```
在上面的例子中,定义了一个名为`myArray`的数组类型的state,并定义了一个名为`setMyArray`的mutation,用于更新`myArray`的值。接下来可以通过调用`commit`方法来触发`setMyArray`mutation的执行,从而更新`myArray`的值。例如:
```
// 假设需要将一个新的数组存储到Vuex中
var newArray = [1, 2, 3];
// 触发mutation来更新myArray的值
store.commit('setMyArray', newArray);
```
要从Vuex中获取存储的数组,可以通过在Vue组件中使用`mapState`辅助函数来获取状态。例如:
```
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['myArray'])
}
}
```
在上面的例子中,通过`mapState`函数将`myArray`映射到当前组件的计算属性中,从而可以在组件中通过`this.myArray`来获取存储在Vuex中的数组。
vue sessionstorage存取对象
Vue 中使用 sessionStorage 存取对象可以使用 JSON.stringify() 和 JSON.parse() 来进行序列化和反序列化。
存储对象:
```
sessionStorage.setItem('key', JSON.stringify(obj))
```
读取对象:
```
let obj = JSON.parse(sessionStorage.getItem('key'))
```
注意:sessionStorage 中的值都是字符串,所以在存储对象时需要先进行序列化,读取时需要进行反序列化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)