1.使用scss
scss是能讓css從屬關系看起來更加直觀
在項目目錄下運行安裝命令:
cnpm install node-sass --save-dev
cnpm install sass-loader --save-dev
然后在項目目錄中的webpack.config.js中的rules里加入配置代碼:
{ test: /\.scss$/, loaders: ['style', 'css', 'sass'] },
如果出現報錯:
Module build failed: TypeError: this.getResolve is not a function
sass-loader的版本過高導致的編譯錯誤,當前最高版本是8.x,需要退回到7.3.1運行
cnpm uninstall sass-loader(卸載當前版本) cnpm install sass-loader@7.3.1 --save-dev cnpm install
2.新建組件
在src目錄下新建目錄components,在components目錄下新建組件取名Home.vue:
<template> <div> <h2>這是一個首頁組件</h2> <button @click="run">彈出首頁組件提示</button> </div> </template> <script> export default { name: 'home', data () { return { msg:'首頁組件' } }, methods:{ run(){ alert(this.msg) } } } </script> <style lang="scss" scoped> h2{ color: red; } </style>
3.在根組件App.vue中引用掛載組件
<template> <div id="app"> <h2>{{msg}}</h2> <v-home></v-home> </div> </template> <script> // 1.引入組件 // 2.掛載組件 // 3.在模板中引用 import Home from './components/Home.vue'; export default { name: 'app', data () { return { msg:'根組件' } }, methods:{ }, components:{ 'v-home':Home } } </script> <style> </style>
組件除了可以在根組件中掛載,也可以在組件之間互相掛載。