天下无坑

天下无坑


vue等待必要数据加载完成后在初始化的方法

<p>应用场景: 直接刷新子路由,父页面的数据还没加载完(如vuex),导致报错</p> <blockquote> <p><strong>计算属性 + immediate侦听</strong></p> </blockquote> <pre><code class="language-javascript">export default { components: { }, data() { return { navTitle: '同行收客图', page: 1 }; }, methods: { // 初始化方法 init() { this.page==1 &amp;&amp; this.getList() }, getList(){ } }, computed: { // ready计算属性,判断一或多个必要的数据,返回 true 或 false ready(){ return this.$store.state.info ? true : false; } }, watch: { 侦听 ready 为真执行初始化方法 'ready': { handler: function(val){ console.log('watch is runed') val &amp;&amp; this.init() }, immediate: true //立刻执行 在mounted之前,如果涉及dom操作则此处应该设置为false,在mounted里初始化 } }, mounted() { //ready &amp;&amp; this.init() }, };</code></pre> <h3>进阶: watch只监视第一次改变</h3> <pre><code> //命令式好处是,可以得到一个取消监听的函数,在需要时取消监听 export default { data: { isReady: false }, mounted() { const unwatch = this.$watch('isReady', function(newValue, oldValue){ console.log(newValue); unwatch() }); }, }</code></pre>

页面列表

ITEM_HTML