文章目录
一、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
重新打包,效果如下
设置省略后缀名: