webpack中使用Vue的配置过程
安装Vue的三种方式
1、直接下载应用
2、CDN引入
3、npm
配置
1、用npm安装vue
npm install --save vue
2、在main.js中引入vue
import Vue from 'vue'
const app=new Vue({
el:'#app',
data:{
message:'hello world'
}
})
3、配置webpack.js
module.export={
resolve:{
alias:{
'vue$':'vue/dist/vue.esm.js'
}
}
}
一、Vue再起步
1.1 使用template
main.js
import Vue from 'vue'
const app=new Vue({
el:'#app',
template:`
<div>
<h2>{{message}}</h2>
<button @click="btnClick">按钮</button>
</div>`
,
data:{
message:'hello world'
},
methods:{
btnClick:function(){
console.log('乔木');
}
}
})
在html中只需要
<body>
<div id="app">
</div>
<script src="dist/bundle.js"></script>
</body>
1.2 抽取template
1、简单抽取
抽取一:
把上文中的template抽取出来
const App={
template:`
<div>
<h2>{{message}}</h2>
<button @click="btnClick">按钮</button>
</div>`
,
data(){
message:'hello'
},
methods:{
btnClick:function(){
console.log('乔木');
}
}
}
在Vue实例中进行注册:
const app=new Vue({
el:'#app',
template:'<App></App>',
components:{
App
}
})
进一步抽取:
上面的变量App可以进一步抽取到/vue/app.js文件中
export default {
template:`
<div>
<h2>{{message}}</h2>
<button @click="btnClick">按钮</button>
</div>`
,
data(){
message:'hello'
},
methods:{
btnClick:function(){
console.log('乔木');
}
}
}
在main.js中进行引入和注册
//引入
import App from './vue/app.js'
const app=new Vue({
el:'#app',
template:'<App></App>',
components:{
//注册
App
}
})
2、抽取到.vue文件中
在vue目录中创建一个App.vue文件:
<!--模板-->
<template>
<div>
<h2 class="title">{{message}}</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<!--js脚本-->
<script>
export default {
name:'App',
data(){
message:'hello'
},
methods:{
btnClick:function(){
console.log('乔木');
}
}
}
</script>
<!--样式-->
<style>
.title{
color: darksalmon;
}
</style>
然后再main.js中进行引入:
import App from './vue/App.vue'
注册方式不变
但是样是无法运行的因为webpack并不认识.vue的文件,所以要安装vue-loader和vue-template-compiler
安装vue-loader、plugin插件
安装过程命令:npm install vue-loader vue-template-compiler --save-d ev
子安在最新版本的vue-loader是15.9.2的版本,所当我们运行这个程序时会报一个错误:
这个问题有两种解决方式一种是降低vue-loader的版本,还有一种办法是安装这个plugin插件
解决方式:
现在webpack.config.js中引入plugin插件:const VueLoaderPlugin=require('vue-loader/lib/plugin')
然后再module.exports中加入属性:
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
]
在运行就可以了
中引入plugin插件:const VueLoaderPlugin=require('vue-loader/lib/plugin')
然后再module.exports中加入属性:
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
]
在运行就可以了