共同学习Vue.js ---webpack中Vue的使用


一、webpack环境中集成Vue.js

1.1 引入Vue.js

在项目中使用Vuejs,那么就必然需要对其有依赖,所以需要先进行安装,因为后续是在实际项目中也会使用Vue的,所以这里安装并不是开发时依赖,也就是并不需要添加 -dev
安装命令:
npm install vue --save

在这里插入图片描述
在项目中使用Vue并打包

1.2 打包项目 – 错误信息

修改完成后,重新打包,运行程序:
打包过程中没有出现任何错误,但是运行程序并没有出现想要的效果,而且浏览器中有报错.

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

在这里插入图片描述

这个错误说的是我们使用的是runtime-only版本的Vue:

  • runtime-only版本: 代码中,不可以有任何的template
  • runtime-compiler版本: 代码中,可以有template,因为有compiler可以用于编译template

解决方法:
在配置文件中配置如图所示:
在这里插入图片描述
效果如图:
在这里插入图片描述

1.3 创建Vue时template 和 el 关系

使用vue进行开发:

// 在main.js中使用vue
// 5.使用Vue进行开发
import Vue from 'vue'
import App from './vue/app'
new Vue({
    el: '#app',
    template: `<App/>`,
    components: {
        App
    }
});

创建新的文件夹,并建立app.js文件

export default {
    template: `
        <div>
            <h2 class="title">{{message}}</h2>
            <button @click="btnClick">按钮</button>
        </div> `,
    data() {
        return {
            message: "Hello Webpack",
            name: "Liu"
        }
    },
    methods: {
        btnClick() {

        }
    }
};

最后执行打包命令 npm run build ; 效果为:
在这里插入图片描述

1.4 .vue文件封装处理

但是一个组件以一个js对象的形式进行组织和使用的时候是非常不方面的

  • 一方面编写template模块非常的麻烦
  • 另外一方面如果样式的话,我们写在哪里合适呢?

这是,我们就可以使用全新的方式来组织一个vue的组件,新建一个App.vue文件如图所示
在这里插入图片描述
在main.js中引入.vue 文件
在这里插入图片描述
在执行打包的时候会出错:

ERROR in ./src/vue/App.vue
Module parse failed: D:\VueWebpack-v0\01-webpack的使用\04-webpack的配置Vue\src\vue\App.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.

显示缺少 vue-loader 以及 vue-template-compiler
执行命令安装:
npm install vue-loader vue-template-compiler --save-dev
修改webpack.config.js 的配置文件
在这里插入图片描述

执行打包后,如果出现报错:

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

可以调节一下vue-loader的版本:
在这里插入图片描述
重新npm install 命令;
如果出现下图所示的错误:
在这里插入图片描述
解决方法: 调节vue 和 vue-template-compiler 的版本保持一致
在这里插入图片描述
重新执行 npm install ; 然后打包测试;结果如下:
在这里插入图片描述
当样式没生效时,需在导入vue的时候后缀一定要加上 .vue
在这里插入图片描述
重新打包,效果如下
在这里插入图片描述
设置省略后缀名:
在这里插入图片描述

1.5 创建.vue的组件

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值