一、初步整合
1. 安装Vue
- 之前项目都是在js文件中直接通过script标签引入Vue,现在模块化思想后,直接通过npm来安装vue;
# vue为运行时依赖
npm install vue --save
2. 在main.js中导入Vue
import Vue from 'vue';
const app = new Vue({
el: "#first",
data: {
name: 'lucy',
address: 'NewYork',
}
})
3. 修改配置文件webpack.config.js
const path = require('path');
module.exports = {
entry: './src/main.js',
output:{
path:path.resolve(__dirname,'dist'),
filename: 'bundle.js',
},
/*引入vue*/
resolve:{
alias:{
'vue$': 'vue/dist/vue.esm.js'
}
}
}
4. 在index.html中展示变量
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack整合Vue</title>
</head>
<body>
<div id="first">
<h2>{{name}}{{address}}</h2>
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
二、单页面复用
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack整合Vue</title>
</head>
<body>
<!--1. 一般不在index.html中写代码
2. 只需要挂载div即可,下面展示的代码全部挪到vue实例的template中-->
<div id="first">
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
2. main.js
import Vue from 'vue';
new Vue({
el: "#first",
/*编译时候,会将template中代码,全部挪到index.html挂载的div中*/
template: `<div>
<h2>{{name}}{{address}}</h2>
</div>`,
data: {
name: 'shuzhan',
address: 'NewYork',
}
})
三、Vue终极使用
1 版本一:main.js中的template模板抽离
import Vue from 'vue';
/*1. 将Vue中的相关数据和逻辑抽取出来*/
const App = {
/*编译时候,会将template中代码,全部挪到index.html挂载的div中*/
template: `<div>
<h2>{{name}}{{address}}</h2>
</div>`,
data(){
return {
name: 'sz',
address: 'pk',
}
}
}
new Vue({
el: "#first",
/*3. 在模板中引用*/
template: '<App/>',
/*2. 将上面组件在Vue实例中做全局注册*/
components:{
App
}
})
2 版本二:上述App抽取为单独的js
App.js
/*到处的是默认的,因此接受方可以随便写名字*/
export default {
template: `<div>
<h2>{{name}}{{address}}</h2>
</div>`,
data(){
return {
name: 'sz',
address: 'pk',
}
}
}
main.js
import Vue from 'vue';
import App from './js/app'/*导入注册的js*/
new Vue({
el: "#first",
/*3. 在模板中引用*/
template: '<App/>',
/*2. 将上面组件在Vue实例中做全局注册*/
components:{
App
}
}
)
3 版本三:app.js抽取为App.vue文件
3.1 vue目录下的文件App.vue
<template>
<!--1. 模板中的东西-->
<div>
<h2 class="title">{{name}}{{address}}</h2>
</div>
</template>
<!--2. 数据,方法等-->
<script>
export default {
name: "App",
data(){
return {
name: 'sz',
address: 'pk',
}
}
}
</script>
<!--3. 样式-->
<style scoped>
.title{
color: red;
}
</style>
3.2 在main.js中引入
import Vue from 'vue';
import App from './vue/App.vue'/*导入对应的Vue文件*/
new Vue({
el: "#first",
/*3. 在模板中引用*/
template: '<App/>',
/*2. 将上面组件在Vue实例中做全局注册*/
components:{
App
}
})
3.3 安装Vue文件加载的loader及配置webpack.config.js
四、多个Vue
- 一般以App.vue作为主文件;
- 其他文件通过子组件的方式注册进App.vue中即可;