[petite-vue學習]--如何使用petite-vue+webpack構建一個多頁面項目

簡介

概述

petite-vue是前段時間剛推出的一個輕量版vue,用法與vue幾乎相同,沒有jquery那些繁瑣的操作和語法,對於熟悉vue語法的用戶來說,兩分鐘就可以上手,唯一的痛點是目前沒有什麼ui框架可以配套使用,需要自己寫一套頁面。

爲了方便開發,我自己用webpack搭建了一套項目模板,有一說一,確實好用,終歸還是拋棄了jquery。項目地址:petite-vue-project

適用情況

  • 項目較小,頁面邏輯簡單
  • 希望使用vue,但是用vue-cli搭建一套項目又覺得繁瑣
  • 替代jquery進行開發

petite-vue

指令

image-20210826153639446

自定義指令

使用方法完全一樣,註冊指令略有區別

// 自定義指令
const vFocus = (ctx) => {
    console.log(ctx)
    ctx.el.focus()
}

createApp({
    store,
})
    .directive('focus', vFocus)
    .mount('#global-state-example')

生命週期

生命週期鉤子函數只有兩個:mountedunmounted

<div v-if="flag" @mounted="handleMount" @unmounted="handleUnmount">
    組件
</div>
createApp({
    flag: false,
    handleSwitchLifeCycle() {
        this.flag = !this.flag
    },
    handleMount() {
        alert('組件被渲染了')
    },
    handleUnmount() {
        alert('組件被銷燬了')
    },
}).mount('#lifecycle-example')

組件

分爲帶模板和不帶模板的組件

// 自定義組件
function WButton(props) {
    // clsssName
    console.log(props)
    return {
        $template: '#w-button',
        ...props,
    }
}
// 註冊組件
createApp({
    WButton,
}).mount('#component-example')
<!-- 按鈕組件 -->
<template id="w-button">
    <button class="btn" :class="`btn-${type}`">
        <span>{{label}}</span>
    </button>
</template>

<!-- 使用組件 -->
<div id="component-example">
    <div
         class="btn-wrapper"
         v-scope="WButton({type:'primary',label:'普通按鈕'})"
         ></div>
    <div
         class="btn-wrapper"
         v-scope="WButton({type:'success',label:'成功按鈕'})"
         ></div>
    <div
         class="btn-wrapper"
         v-scope="WButton({type:'danger',label:'危險按鈕'})"
         ></div>
</div>

狀態管理

使用·reactive方法來創建全局狀態管理

// 全局狀態管理
const store = reactive({
  text: '',
})

// 註冊 store
createApp({
  store,
}).mount('#global-state-example')

使用時通過store對象找到對應狀態

<input type="text"  v-model="store.text" placeholder="輸入一些值試試" />

至此爲止介紹了petite-vue的一些關鍵語法,還有一些細節東西沒有仔細瞭解,但是掌握這些基本差不多了

快速開發的腳手架

對於petite-vue沒有像vue-cli那樣用於快速開發的腳手架,自己寫一套簡單的。

多頁面入口

說白了,這就是類似jquery的一個庫,他不是vue那種單頁面的應用,所以需要配置多入口

  entry: {
    index: path.resolve(__dirname, '../src/pages/index/index.js'),
    dashboard: path.resolve(__dirname, '../src/pages/dashboard/index.js'),
  },

html模板

針對不同頁面配置了不同的模板

new HtmlWebpackPlugin({
    title: '登陸',
    filename: 'index.html',
    template: path.resolve(__dirname, '../src/pages/index/index.html'),
    // chunks: ['index', 'petiteVue'],
    chunks: ['index'],
    hash: true,
    minify: {
        collapseWhitespace: true,
        removeComments: true,
    },
}),
    new HtmlWebpackPlugin({
    title: '遠程控制',
    filename: 'dashboard.html',
    template: path.resolve(__dirname, '../src/pages/dashboard/index.html'),

    chunks: ['dashboard'],
    hash: true,
    minify: {
        collapseWhitespace: true,
        removeComments: true,
    },
}),

提取公共部分代碼

每個頁面都需要引入一次petite-vue,還有一些公共樣式,這些都需要把他們提取出來

optimization: {
    splitChunks: {
        cacheGroups: {
            common: {
                name: 'commons',
                chunks: 'all',
                minChunks: 2,
            },
        },
    },
},

devServer

爲了避免每次更改頁代碼都需要手動去刷新瀏覽器頁面

devServer: {
    // hot: true,
    disableHostCheck: true,
    inline: true,
    port: 4001,
    open: true,
    openPage: 'index.html',
    contentBase: [
        path.resolve(__dirname, '../src/pages/index'),
        path.resolve(__dirname, '../src/dashboard/index'),
    ],
},

全局環境變量

webpack5 不兼容process.env,手動去定義全局變量

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('development'),
    'process.env.BASE_URL': JSON.stringify(EnvConfig.DEV_URL),
}),

本地跨域

最常見的跨域問題

proxy: {
    '/dev': {
        target: EnvConfig.DEV_URL,
        changeOrigin: true,
        pathRewrite: {
            '^/dev': '',
        },
        logLevel: 'debug',
    },
},

打包時壓縮css,通過link標籤引入

  new MiniCssExtractPlugin({
      filename: 'css/[name].[hash].css',
    }),

支持scss

{
    test: /\.scss$/,
    use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},

js兼容問題

babel-loader+ core-js實現兼容

  {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                useBuiltIns: 'usage',
                corejs: {
                  version: 3,
                },
                targets: {
                  chrome: '60',
                  firefox: '60',
                  ie: '9',
                  safari: '10',
                  edge: '17',
                },
              },
            ],
          ],
        },
      },

總結

整個項目已經上傳到了github上:項目地址

至此爲止,一個項目的骨架基本算是完成了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章