一、初步整合
1. 安装Vue
之前项目都是在js文件中直接通过script标签引入Vue,现在模块化思想后,直接通过npm来安装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',
},
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>
<div id="first">
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
2. main.js
import Vue
from 'vue';
new Vue({
el
: "#first",
template
: `<div>
<h2>{{name}}{{address}}</h2>
</div>`,
data
: {
name
: 'shuzhan',
address
: 'NewYork',
}
})
三、Vue终极使用
1 版本一:main.js中的template模板抽离
import Vue
from 'vue';
const App
= {
template
: `<div>
<h2>{{name}}{{address}}</h2>
</div>`,
data(){
return {
name
: 'sz',
address
: 'pk',
}
}
}
new Vue({
el
: "#first",
template
: '<App/>',
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'
new Vue({
el
: "#first",
template
: '<App/>',
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'
new Vue({
el
: "#first",
template
: '<App/>',
components
:{
App
}
})
3.3 安装Vue文件加载的loader及配置webpack.config.js
四、多个Vue
一般以App.vue作为主文件;其他文件通过子组件的方式注册进App.vue中即可;
转载请注明原文地址:https://blackberry.8miu.com/read-10336.html