1. 程式人生 > 實用技巧 >vue.js模組化開發

vue.js模組化開發

//下面是匯入app.vue
import app from './vue/app.vue'

new Vue({
    el:'#app',
    // tempalte會完全替換掉id為app的div裡面的內容,所以使用了<app/>
    template:'<app/>',
    components:{
        app
    }
})

  上面是main.js中的程式碼

<template>
<div >
    {{msg}}
    <button @click="btnclick()">hello world</button>
    <h2 class="title">....</h2>
</div>
</template>

<script>
export default {
    name:'app',
    data(){
        return{
            msg:'hello world'
        }
    },
    methods:{
        btnclick:function(){
            alert('hello world')
        }
    }
}
</script>

<style>
.title {
    background-color: brown;
}
</style>

  上面是app.vue中的程式碼

執行時需要先安裝npm install --save-dev vue-loader vue-template-compiler(vue-loader)

這個完成後再執行npm run build會出現

vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your webpack config.

需要在webpack.config.js中引入檔案

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = { entry:'./src/main.js', output:{ //動態獲取路徑 path:path.resolve(__dirname,'dist'), filename:'bundle.js', publicPath:"dist/" }, module:{ rules: [ { // $表示結尾 test: /\.css$/, //style-loader負責將樣式新增到DOM中 //css-loader只負責載入,不負責解析 //使用多個loader時,是從右向左的 use: ['style-loader', 'css-loader' ] }, { test: /\.less$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "less-loader" } ] }, { test: /\.(png|jpg|gif)$/, use: [ { loader: 'url-loader', options:{ //當圖片的體積大於limit時,會自動使用file-loader轉換成檔案形式,而不會轉換成base64格式 limit:1000, //[]是一個變數 name:'img/[name].[hash:8].[ext]' } }, ] }, { test:/\.vue$/, use:['vue-loader'] } ] }, resolve: { //alias:別名 alias: { 'vue$': 'vue/dist/vue.esm.js' } }, plugins:[ new VueLoaderPlugin() ]
}