【问题标题】:Why vue cli 3 template or any other template has `h => h(App)` on main.js instead of just `new Vue(App)`?为什么 vue cli 3 模板或任何其他模板在 main.js 上有 `h => h(App)` 而不仅仅是 `new Vue(App)`?
【发布时间】:2020-10-09 07:22:51
【问题描述】:
如果您打开任何 CodeSandbox Vue 模板或 vue-cli 3 模板,您可以在 main.js 中注意到此代码
方法一
new Vue({
render: (h) => h(App),
}).$mount("#app");
我对这段代码有点困惑,为什么不直接
方法二
new Vue(App).$mount("#app");
写Method 1有什么好处吗?
【问题讨论】:
标签:
vue.js
vuejs2
vue-component
【解决方案1】:
是的,有一个好处——当你使用 options 对象时,你还可以添加 Vue-Router、Vuex,定义一些数据、计算属性、观察者、方法甚至一些生命周期钩子。例如:
new Vue({
data:
{
currentUser: null,
lastError: null,
showLoadingSpinner: false,
},
computed:
{
baseURL()
{
return process.env.BASE_URL;
}
},
created()
{
this.$on('logout', this.logout);
},
beforeDestroy()
{
this.$off('logout', this.logout);
},
router: myRouter,
store: myStore,
render: h => h(App),
}).$mount('#app');