v-if & v-for 理解
阿新 • • 發佈:2022-03-19
先上程式碼,通過 script 標籤方式引入 vue.js(2.x版本)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>v-if&v-for</title> </head> <body> <div id="demo"> <h4>v-if 與 v-for 的優先順序問題</h4> <p v-if="isShow" v-for="(item,i) in children">{{ item.title }}</p> </div> <!-- <script src="vue.js"></script> --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> const app= new Vue({ el: '#demo', data() { return { name: '彭', children: [{ title: '標題一' }, { title: '標題一' }], isShow: true }; } }); console.log(app.$options.render); </script> </body> </html>
在打印出的 app.$options.render 中會發現,v-for 優先順序高於 v-if
(function anonymous() { with (this) { return _c('div', { attrs: { "id": "demo" } }, [_c('h4', [_v("v-if 與 v-for 的優先順序問題")]), _v(" "), _l((children), function(item, i) { return (isShow) ? _c('p', [_v(_s(item.title))]) : _e() })], 2) } } )
那 vue3.x版本呢?