使用vue組件搭建網頁應用
- 搭建開發環境
- 開發組件
搭建開發環境
搭建一個 vue 項目最快的方式就是使用 vue cli 腳手架進行初始化,包含了所有完整的依賴及開發配置。
首先全局安裝 vue cli,打開 cmd 命令提示符 或者 power shell,輸入以下命令:
npm install -g @vue/cli
如果出現以下錯誤,則表示沒有安裝 NodeJS,下載 NodeJS 安裝即可。
全局安裝好 vue cli 后,使用下面的命令初始化一個簡單模板,中途會詢問一些選項,全部默認回車就好
vue create vue-demo
初始化完成后項目結構如下,使用編輯器打開項目,推薦 vscode。
繼續在 cmd 命令提示符中輸入以下命令:
cd vue-demo
npm run serve
在瀏覽器中打開 http://localhost:8080/
查看效果圖
開發組件
這里我們關注的重點是 /src
文件夾下的內容。
在 src/components
目錄下新建文件 PageBanner.vue
,復制以下代碼
<template><div class="page-banner"><img :src="image" alt="" /></div>
</template><script>
export default {name: "PageBanner",data() {return {image: "../assets/banner.png", // 這里替換成自己的圖片,可以是外部鏈接};},
};
</script>
<style>
.page-banner {width: 100%;height: 100vh;overflow: hidden;position: relative;
}
.page-banner img {width: 100%;height: 100%;object-fit: cover;
}
</style>
在 src/components
目錄下新建文件 HeaderNavigation.vue
,復制以下代碼
<template><div class="nav"><ul><template v-for="item in items" :key="item"><li><a :href="item.url">{{ item.txt }}</a><SecNav v-if="item.children" :items="item.children"></SecNav></li></template></ul></div>
</template><script>
import SecNav from "./SecNav.vue";export default {name: "HeaderNavigation",components: { SecNav },data() {return {items: [{ txt: "主頁", url: "/" },{ txt: "聯系我們", url: "/" },{txt: "服務內容",url: "/",children: [{ txt: "火星旅行", url: "/" },{ txt: "仙女星旅行", url: "/" },{ txt: "M77旅行", url: "/" },],},{txt: "售前咨詢",url: "/",children: [{ txt: "旅行路線", url: "/" },{ txt: "安全保障", url: "/" },{ txt: "自助查詢", url: "/" },{ txt: "人工客服", url: "/" },],},{ txt: "投訴建議", url: "/" },],};},
};
</script><style>
.nav {position: absolute;width: 100%;background: #fff;z-index: 1;
}
.nav > ul {display: flex;list-style: none;margin: 0;justify-content: space-around;
}
.nav > ul li {flex-grow: 1;padding: 15px 20px;text-align: center;position: relative;
}
.nav > ul li:hover {background-color: #2289ff;cursor: pointer;
}
.nav > ul li:hover > a {color: white;
}
.nav > ul li:hover .sec-nav {display: inline-block;z-index: 2;
}
.nav > ul li a {display: inline-block;width: 100%;color: #2289ff;text-decoration: none;
}
</style>
在 src/components
目錄下新建文件 SecNav.vue
,復制以下代碼
<template><ul class="sec-nav"><template v-for="item in items" :key="item"><li><a :href="item.url">{{ item.txt }}</a></li></template></ul>
</template><script>
export default {name: "SecNav",props: ["items"],
};
</script><style>
.sec-nav {position: absolute;background-color: #fff;display: none;left: 0;top: 100%;width: 100%;padding: 0;
}
.sec-nav li {list-style: none;
}
</style>
修改 src/App.vue
,復制以下代碼
<template><HeaderNavigation /><PageBanner />
</template><script>
import PageBanner from "./components/PageBanner.vue";
import HeaderNavigation from "./components/HeaderNavigation.vue";export default {name: "App",components: {PageBanner,HeaderNavigation,},
};
</script><style>
body {margin: 0;
}
</style>
效果圖