vue单文件组件

1.传统组件的问题和解决方案

(1)问题

  • 全局定义的组件必须保证组件的名称不重复
  • 字符串的语法缺乏高亮,在HTML有多行的时候,需要用到丑陋的‘\’
  • 不支持CSS
  • 没有构建步骤限制,只能使用HTML和ES5,不能使用babel之类的预处理器

(2)解决方案

针对传统组件的问题,Vue提供了一个解决方案---使用Vue单文件组件

2.Vue单文件组件的基本用法

单文件组件的组成结构:

template   组件的模板区域

script   业务逻辑区域

style   样式区域

3.webpack中配置vue组件的加载器

1.运行:npm i vue-loader vue-template-compiler -D

2.在webpack.config.js文件中,添加vue-loader配置如下:

4.在webpack中使用vue

1.运行 npm i vue -S 安装 vue

2.在src -> index.js 入口文件中,通过 import Vue from 'vue' 来导入vue构造函数

3.创建vue的实例对象,并制定要控制的el区域

4.通过render函数渲染App根组件

import Vue from 'vue'
import App from './components/App.vue'

const vm = new Vue({
    el:'#app',
    // 用render渲染指定的组件
    render: h => h(App)
})

5.webpack打包发布

上线之前需要通过webpack将应用进行整体打包,可以通过package.json文件配置打包命令

添加完build后,删除dist文件,运行命令 npm run build ,这时候你会发现dist目录被打包生成了

webpack.config.js:

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebPackPlugin({
    template:'./src/index.html',
    filename:'index.html'
})
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    mode: 'development',
    // 上线时要将development改为production
    entry: path.join(__dirname,'./src/index.js'),//输入文件存放路径
    output: {
        path: path.join(__dirname,'./dist/'),//输出文件存放路径
        filename: 'bundle.js'//输出文件的名称
    },
    plugins:[htmlPlugin,new VueLoaderPlugin()],
    module:{
        rules:[
            {test:/\.css$/,use:['style-loader','css-loader','postcss-loader']},
            {test:/\.less$/,use:['style-loader','css-loader','less-loader']},
            {test:/\.scss$/,use:['style-loader','css-loader','sass-loader']},
            {test:/\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/,use:'url-loader?limit=16941'},
            {test:/\.js$/,use:'babel-loader', exclude:/node_modules/},
            {test:/\.vue$/,use:'vue-loader'}
           ]
          }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值