VUE 在一個元件中引用另外一個元件的兩種方式
阿新 • • 發佈:2020-08-07
背景:比如在一個vue寫成的頁面中,想要使用一個vue完成的表格元件(這個表格元件也是一個XXX.vue檔案),具體的怎麼在一個檔案中引入需要使用的那部分內容,比如前面的表格、比如某個餅圖圖表什麼的。
下面有兩種方法:
方法一:程式碼如下
<template> <div> <!-- 3.在template中就可以直接使用了 --> <testComponent></testComponent> </div> </template> <script> //1.先使用import匯入你要在該元件中使用的子元件 import testComponent from'./testComponent.vue' export default { //2.然後,在components中寫入子元件 components: {testComponent}, methods: {}, } </script> <style></style>
方法二:程式碼如下
<template> <div> <!--2.在template 中使用--> </div> </template> export default { //1.直接在components屬性中寫入子元件 components: { testComponent:require('./testComponent.vue').default }, methods: {}, }</script> <style></style>
<template> <div> <!--2.在template 中使用--> </div> </template> export default { //1.直接在components屬性中寫入子元件 components: { testComponent:require('./testComponent.vue').default }, methods: {}, } </script> <style></style>
兩者之間的區別:初學者暫時沒發現啥顯著的區別,第一種應該是使用的es6的引入機制,第二種使用的是es5
的機制,所以,推薦還是使用第一種好點。
//正常載入
import index from '../pages/index.vue'
import view from '../pages/view.vue'
//懶載入
const index = resolve => require(\['../pages/index.vue'\], resolve)
const view = resolve => require(\['../pages/view.vue'\], resolve)
//懶載入 \-
按組 const index = r => require.ensure(\[\], () => r(require('../pages/index.vue')), 'group-index')
const view = r => require.ensure(\[\], () => r(require('../pages/view.vue')), 'group-view')
// 懶載入 \- 按組 import,基於ES6 import的特性
const index = () => import('../pages/index.vue')
const view = () => import('../pages/view.vue')
原文連結:https://www.cnblogs.com/feicheninfo/articles/10411955.html