什么是可以访问localStorage的vue实例的最早生命钩子?

时间:2017-07-30 17:50:54

标签: vue.js

什么是可以访问localStorage和其他DOM API的vue实例的最早生命挂钩?

1 个答案:

答案 0 :(得分:0)

我想说他们所有人都可以访问localStorage,因为当Vue接管控制权时,window(和window.localStorage)已经存在。就是beforeCreate。但您可以尝试:

Vue.component('test-component', {
  data: function() { return { hello: "Hello World!" }},
  template: '<div>{{ hello }}</div>',
  beforeCreate: function() {console.log("beforeCreate has access to localStorage?", typeof localStorage === "object") },
  created: function() {console.log("Created has access to localStorage?", typeof localStorage === "object") },
  mounted: function() {console.log("Mounted has access to localStorage?", typeof localStorage === "object") },
});

var app = new Vue({
  el: '#app',
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <test-component />
</div>

看起来像SO沙箱不允许访问localStorage。改为选中此pen