将组件定义成一个js和css,然后供其他页面进行调用
demo.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <link type="text/css" rel="stylesheet" href="./module1.css"> </head> <body> <!-- 引入的组件,每个组件拥有一个自己的样式文件和一个js文件 --> <div id="demoContainer"> <module1 :select-index="selectedIndex[0]"></module1> <br/> <module1 :select-index="selectedIndex[1]"></module1> <br/> <module1 :select-index="selectedIndex[2]"></module1> </div> </body> <script type="text/javascript" src="./module1.js"></script> <script type="text/javascript"> var vvv = new Vue({ el: '#demoContainer', data: { selectedIndex: [1,2,0] }, components: { Module1 } }) </script> </html>
module1.css
.module1 .item-select{background-color: green;color: red;}
module1.js
var module1Content = ` <div class="module1"> <ul> <li v-for="(language, index) in languageList" :key="language" :class="selectBg(index)">{{ language }}</li> </ul> </div> ` var Module1 = { data: function(){ return { languageList: ['Java','JavaScript','C++','Python','Php'] } }, props: { selectIndex: Number }, methods:{ selectBg: function(num){ if(this.selectIndex == num){ return 'item-select' } } }, template: module1Content }
效果图如下: